7

I am trying to write a quick snippet to demonstrate the difference between an immutable and mutable type. Does this code seem to right to you all?

class MutableTypeExample
{
    private string _test; //members are not readonly
    public string Test
    {
        get { return _test; }
        set { _test = value; } //class is mutable because it can be modified after being created
    }

    public MutableTypeExample(string test)
    {
        _test = test;
    }

    public void MakeTestFoo()
    {
        this.Test = "FOO!";
    }
}

class ImmutableTypeExample
{
    private readonly string _test; //all members are readonly
    public string Test
    {
        get { return _test; } //no set allowed
    }

    public ImmutableTypeExample(string test) //immutable means you can only set members in the consutrctor. Once the object is instantiated it cannot be altered
    {
        _test = test;
    }

    public ImmutableTypeExample MakeTestFoo()
    {
        //this.Test = "FOO!"; //not allowed because it is readonly
        return new ImmutableTypeExample("FOO!");
    }
}
2
  • It's not the class that is mutable but a field. You can mix up readonly and "normal" fields in a class as long as readonly fields are only assigned in the constructor code or at initialization time.
    – Matten
    Commented Aug 16, 2011 at 13:26
  • ImmutableTypeExample MakeTestFoo() doesn't make much sense. Is it supposed to be static?
    – Bala R
    Commented Aug 16, 2011 at 13:26

2 Answers 2

14

Yup, that looks reasonable.

However, I would also talk about "leaky" mutability. For example:

public class AppearsImmutableButIsntDeeplyImmutable
{
    private readonly StringBuilder builder = new StringBuilder();
    public StringBuilder Builder { get { return builder; } }
}

I can't change which builder an instance appears on, but I can do:

value.Builder.Append("hello");

It would be worth you reading Eric Lippert's blog post on kinds of immutability - and indeed all the rest of the posts in the series.

2
  • In other words, the example only works because the string property it uses also happens to be immutable. As soon as you have a mutable property, even if it only available via a getter, you aren't fully immutable. Commented Oct 20, 2011 at 21:45
  • You might also reason about collections, immutable/mutable class pairs etc. I wrote an article on that recently that should be interesting in this context: rickyhelgesson.wordpress.com/2012/07/17/… Commented Jul 31, 2012 at 8:06
5

Yes, that looks right.

Note that the private members doesn't need to be readonly for the class to be immutable, that is just an extra precaution agains broken code inside the class.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.