jimmyfever
jimmyfever

Reputation: 387

Is a class immutable if its readonly fields are not immutable?

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

Answers (4)

myermian
myermian

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.

  • private field arrays marked as readonly are immutable, but that doesn't mean you can't replace the indexes with different values. A way to solve this is to return a copy of the array or an enumeration of the array
  • The objects of the array may or may not be immutable. Whether you make them immutable or you return clones of the them or whatever, that's really up to you.

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

Ryan Byrne
Ryan Byrne

Reputation: 860

I think its immutable if it follows three principals:

  • Make the fields private readonly.
  • Provide a public property get accesor.
  • If the class is not longer needed to be inherited, make it sealed.

These are not hard and fast rules with a strict definition of immutable. They are just guidelines.

Upvotes: 0

svick
svick

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

Josh Austin
Josh Austin

Reputation: 776

This class is not immutable since it can be inherited and have other things added it.

Upvotes: 0

Related Questions