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?
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.