Reputation: 538
I am trying to create an extension class of JObject, which is immutable.
If I create a class like below, can it prevent the actual JObject being modified?
public class ImmutableJObejct: JObject
{
public readonly JObject JObject;
public ImmutableJObejct(JObject jObject)
{
this.JObject = jObject;
}
}
Which is the right approach? should I not be expending the code and implement each methods that I need from JOBject?
Upvotes: 2
Views: 185
Reputation: 13561
To answer your question: Yes and no. Or "it depends".
There are basically 2 kinds of immutable objects: "shallow" immutable objects where all properies are readonly and does not have any methods that modify state, and "deep" immutable objects where not only are all properties readonly, they are also either themselves immutable or copies of a mutable object.
Your example is an example of a shallow immutable object. It doesn't allow you to give your ImmutableJobject a new JOject once it is created, but you can possibly change properties on that object. To make it a deep immutable object, the field JObject needs to be changed to a readonly property, that creates a new JObject everytime it is accessed.
Update: As with all things, immutablility comes with cost and benefits. The primary cost is in the need to create more objects, either to capture a new state, or to keep deep immutable objects from having their properties changed. Depending upon how many such objects are created and how long they are tracked/referenced, this can impact both cpu and memory. Unless you control all of the objects in the object's graph/hierarchy, there is little you can do to avoid this cost.
Upvotes: 2
Reputation: 2062
Basically you could return a new instance of JObject each time.
public class ImmutableJObejct
{
private readonly JObject _jObject;
public ImmutableJObejct(JObject jObject)
{
_jObject = jObject;
}
public JObject JObject
{
get { return new JObject(_jObject); }
}
}
Upvotes: 2