C# and immutability and readonly fields… a lie?

前端 未结 5 1089
攒了一身酷
攒了一身酷 2020-12-05 03:53

I have found that People claim that using all readonly fields in a class does not necessarily make that class\'s instance immutable because there are \"ways\" to change the

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 04:39

    EDIT: I've concentrated on code working "within" the system as opposed to using reflection etc as Eric mentions.

    It depends on the type of the field. If the field itself is of an immutable type (e.g. String) then that's fine. If it's StringBuilder then the object can appear to change even though the fields themselves don't change their values, because the "embedded" objects can change.

    Anonymous types are exactly the same. For example:

    var foo = new { Bar = new StringBuilder() };
    Console.WriteLine(foo); // { Bar = }
    foo.Bar.Append("Hello");
    Console.WriteLine(foo); // { Bar = Hello }
    

    So, basically if you have a type that you want to be properly immutable, you need to make sure it only refers to immutable data.

    There's also the matter of structs which can have readonly fields but still expose methods which mutate themselves by reassigning this. Such structs behave somewhat strangely depending on the exact situation in which you call them. Not nice - don't do it.

    Eric Lippert has written a great deal about immutability - it's all gold, as you'd expect... go read :) (I hadn't noticed that Eric was writing an answer to this question when I wrote this bit. Obviously read his answer too!)

提交回复
热议问题