C# and immutability and readonly fields… a lie?

前端 未结 5 1110
攒了一身酷
攒了一身酷 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:41

    I think Eric's answer is far beyond the scope of the original question, to the point of not even answering it, so I'll take a stab at it:

    What is readonly? Well, if we're talking about value types, it's simple: Once the value type is initialized and given a value, it can never change (at least as far as the compiler is concerned).

    The confusion starts to set in when we talk about using readonly with reference types. It's at this point we need to distinguish the two components of a reference type:

    • The "reference" (variable, pointer) which points to the address in memory where your object lives
    • The memory that contains the data the reference is pointing to

    A reference to an object is itself a value type. When you use readonly with a reference type, you are making the reference to your object immutable, not enforcing immutability on the memory in which the object lives.

    Now, consider an object that contains values types and references to other objects, and those objects contain value types and references to other objects. If you were to compose your objects in such a way that all fields in all objects are readonly you can, in essence, achieve the immutability you desire.

提交回复
热议问题