开发者

Immutable vs Mutable C#

开发者 https://www.devze.com 2023-03-28 16:12 出处:网络
I am trying to write a quick snippet to demonstrate the difference between an immutable and mutable type.

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()
    {
        //t开发者_如何转开发his.Test = "FOO!"; //not allowed because it is readonly
        return new ImmutableTypeExample("FOO!");
    }
}


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号