Immutable vs Mutable C #

I'm trying to write a quick snippet to demonstrate the difference between immutable and mutable type. Does this code seem to suit 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!");
    }
}
+5
source share
2 answers

Yes, that looks reasonable.

However, I would also talk about “leaky” variability. For instance:

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

I cannot change which instance I built, but I can do:

value.Builder.Append("hello");

It would be helpful to read Eric Lippert's blog post on types of immutability - and indeed all the other posts in the series.

+14
source

Yes, it looks right.

, readonly , , .

+4

All Articles