Given,
public class SomeClass {
public string SomeName{get;}
public List<string> RelatedNames{get;}
}
public class Program{
public void Main(){
var someClassInstance = new SomeClass(){ SomeName = "A", RelatedNames = new List<string>(1){ "a" }};
// So, now someClassInstance have been allocated some memory in heap = 1 string object and a list with 1 string object.
// Since SomeClass is mutable, it could be modified as below
someClassInstance.SomeName = "Now This is much more than a name";
someClassInstance.RelatedNames = someClassInstance.RelatedNames.AddRange(new List<string>(100} { "N","o","w".....});
//Now what happens inside heap?
//1.someClassInstance.SomeName will move it's pointer to another string inside heap
//2.someClassInstance.RealtedNames will move it's pointer to another List<>(101) inside heap.
//Is it correct? Then where is 'mutability' ?
}
}
As mentioned in the comments above, “AFAIK” on modifying a mutable object the internal pointers of that object will just point to another memory location inside heap. If that is correct, then does that mean that all objects inside heap (reference type) are immutable?
Thanks for your interest.
Where’s mutability? Right there:
You just mutated the object pointed to by
someClassInstance.Also, your example is a bit contrived.
Strings are indeed immutable, butLists are not, so you could have done this:And then you just mutated the object pointed to by
someClassInstance.RelatedNames.EDIT: I see you changed your question. Well, then:
1is true becauseStringwas designed to be immutable. That’s why there’s theStringBuilderclass in case you need a mutable string.2is false, because that’s not howListis implemented. Perhaps that’s where your confusion comes from. Still, when you invokeAddRange,someClassInstance.RelatedNameswill still point to the same instance, but that instance’s internal state will have changed (most likely, its backing array will have been changed to point to a different array object, and its count would now be101). In fact, a reference cannot magically change based on the operations that are invoked to the object it refers to.And none of that changes the fact that
someClassInstance‘s internal state was mutated anyway.