Is it correct that it is not possible to change the value of an immutable object?
I have two scenarios regarding readonly
that I want to understand:
What if I have a collection and mark it as readonly
, like the following. Can I still call _items.Add
?
private readonly ICollection<MyItem> _items;
And also for the following variable, if later on I call _metadata.Change
which will change the internal values of a couple member variable in the Metadata
instance. Is _metadata
still immutable?
private readonly Metadata _metadata;
For both variables above, I totally understand that I can't directly assign new values to them outside of initializer and constructors.
There's a subtle difference between read-only and immutable. The former cannot be re-assigned once initialized, for the latter there is no way to change the state of the object/field.
The readonly keyword is a modifier that can be used in four contexts: In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class.
In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.
When you create a string, it is immutable. That means it is read-only. When something is immutable or read-only, it means it cannot be changed at a later time.
I suggest you to read the series of blog posts by Eric Lippert. The first part is Immutability in C# Part One: Kinds of Immutability. Very informative and helpful, as always. The series describes what does it mean for a variable to be readonly, immutable etc. in details.
Generally, readonly
means only that you can't re-assign a field outside the constructor. The field itself can be modified as long as it stays the same instance. So yes, you can add elements to the collection stored in readonly
field.
About mutability, this is more complex and it depends a bit what kind of mutability you consider. When Metadata
internal values are references and those references itself (the instances it point to) doesn't change, you could say Metadata
stays not mutated. But it is mutated logically. See Eric's posts for more insights.
Marking a field as read-only only means that you cannot change the value of that field. It has no bearing on the internal state of the object there. In your examples, while you would not be able to assign a new metadata object to the _metadata field, nor a new ICollection to the _items field (outside of a constructor that is), you can change the internal values of the existing objects stored in those fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With