Situation:
I often run into this problematic and never know how to solve it. Though I don’t know where and how to look for answer.
So here it is. When you store some objects into other objects you can have them as readonly, or just with a getter, which is the same. This way you cannot change the value of a MyInt in
public class ClassA {
public readonly int MyInt;
public string MyString;
}
and no problem if I want to put this in a container as follows:
public class ClassB {
public readonly ClassA MyClassA;
public string MyString;
}
This will still work as expected. MyInt is readonly and MyStringA is not.
Problem:
But I can still get MyClassA and set MyClassA.MyStringA.
Is there a way to have a “stricter” readonly system?
With the above example I would like MyClassA’s fields to be all readonly if MyClassA is.
The only solution I can think of is to have another class MyClassAreadonly. But that seems ugly and not not convenient.
Context:
The reason why I am looking for this behavior is that I want MyClassB.MyString to add logic (like firing an event) before setting MyClassB.MyClassA.MyString. So another solution is to simply not show ClassB.MyClassA by setting it as private. But that is nice to being able to retrieve MyClassA! But if I retrieve it and modify it I miss the ClassB logic!
PS: Despite I can’t figure it out, I hope to have been clear enough.
“Deep” immutability
As stated in a comment by @Damien_The_Unbeliever, here is a perfect “answer” to my question. I put answer between quote marks because there is no built-in solution for the moment in C#.
The closest alternative to address my issue will be to have an Immutable facade for the objects (MyClassA) I want to use this way.
Thanks Damien.
Another read on the subject: http://www.bluebytesoftware.com/blog/2007/11/11/ImmutableTypesForC.aspx