I am trying to write a C# version of a Java class. If we call our class MyRequest
, we are dealing with a field called _body
which is a JSONObject
. Here is a simplified version of my class with only this field.
Java:
public class MyRequest {
JSONObject _body = new JSONObject();
/**
* Pass a String formatted json as the request body
* @param json
* @return the request itself
*/
public MyRequest setBody(String json) {
_body = new JSONObject(json);
return this;
}
/**
* Pass a JSONObject formatted json as the request body
* @param json
* @return the request itself
*/
public MyRequest setBody(JSONObject json) {
return setBody(json.toString());
}
/**
* Use an HashMap to build the body
* @param json
* @return the request itself
*/
public MyRequest setBody(HashMap<String, Object> json) {
_body = new JSONObject(json);
return this;
}
/**
* Body getter
* @return the stringified body
*/
public String getBody() {
return _body.toString();
}
@Override
public String toString() {
return new JSONObject()
.put("Resource", _resource)
.put("ID", _id)
.put("Action", _action)
.put("Action ID", _actionId)
.put("Filters", _filters.toString())
.put("Body", _body.toString())
.toString();
}
}
As we can see our _body
field has three different setters and the class also overrides the ToString()
method. I'd like to write a C# equivalent to this class without calling my getter and setter methods GetBody()
and SetBody()
.
The equivalent for JSONObject
in C# will be a JObject
which comes from Newtonsoft JSON library. I have written the override as following (this however is not the main problem):
public override string ToString()
{
return new JObject()
{
{"Body",_body.ToString()}
}.ToString();
}
I would like the class to follow C# coding standards. They usually come with a pattern like this:
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
So how can we have the same behavior for this Java class in C#?
I would normally have a property with the same type as you want to expose with the getter, and then have additional SetBody
methods. So potentially:
private JObject body;
public string Body
{
get { return body.ToString(); }
set { body = JObject.Parse(value); }
}
public void SetBody(JObject body)
{
this.body = body;
}
public void SetBody(IDictionary<string, object> body)
{
...
}
However:
JObject
in the SetBody(JObject)
method, as otherwise it will behave quite oddlystring
property with an underlying JObject
variable could end up being expensive... evaluating a property is usually expected to be cheap.See more on this question at Stackoverflow