What does immutable and readonly mean in C#?

前端 未结 8 962
我寻月下人不归
我寻月下人不归 2021-02-13 09:44

Is it correct that it is not possible to change the value of an immutable object?

I have two scenarios regarding readonly that I want to understand:

8条回答
  •  隐瞒了意图╮
    2021-02-13 10:15

    An immutable object is one that cannot be changed, once created. In C# strings are immutable. If you look at the string manipulation routines you can see that all of them return a new, modified, string and leaves the original string unchanged.

    This facilitates the string handling considerably. When you have a reference to a string, you can be sure that noone else will unexpectedly change it under your feet.

    readonly is something else. It means that the reference cannot be changed, once set and that it can only be set during object construction. In your examples you can change the contents of _items or the properties of _metadata, but you cannot assign another ICollection to the _items member or another Metadata instance to _metadata.

    readonly is set on the reference to an object. Immutability is a property of the object itself. These can be freely combined. To make sure that a property is not changed in any way, it should be a readonly reference to an immutable object.

提交回复
热议问题