Reputation: 387
If I have a C# class with only readonly fields, but the fields' types are NOT immutable, is the class considered immutable?
Is this class immutable?
public class Foo
{
private readonly int[] _blah;
public Foo(int[] blah)
{
_blah = blah;
}
public int[] Blah { get { return _blah; } }
}
_blah is not immutable, since I can change the members of the array, though the array member variable can never change.
So, is a class immutable if its fields are all readonly, or is a class immutable only if its fields are not only readonly, but also immutable themselves?
Upvotes: 1
Views: 229
Reputation: 32515
It will really depend on who you ask or what you mean. Some might say that the class itself is immutable because its direct members are immutable. Some might say that the class and all its members (and their properties, etc) -- basically, the entire object graph -- must be immutable in order to be considered immutable.
In your situation, the objects are integers (which are immutable), but your array itself isn't (again, depending what you define as immutable). If all you want to guarantee is the private field can't be altered and don't care about the indexes, then you're fine. But, if you want the indexes to be locked in then you need to expose your array in another way.
Also, a nice collection to look into is the ReadOnlyCollection<T>
. It is a collection that holds a reference to the original collection (it wraps it), so that the indexes can't be changed.
Also, point in case... already you have varying answers to the degree of what "immutable" actually means.
Upvotes: 1
Reputation: 860
I think its immutable if it follows three principals:
These are not hard and fast rules with a strict definition of immutable. They are just guidelines.
Upvotes: 0
Reputation: 244777
Instances of this class are not immutable, because you can mutate their contents. E.g. foo.Blah[0] = 42;
. But if you changed the Blah
property to IEnumerable<int>
or IReadOnlyList<int>
, the instances would be considered immutable.
Upvotes: 1
Reputation: 776
This class is not immutable since it can be inherited and have other things added it.
Upvotes: 0