What does immutable and readonly mean in C#?

前端 未结 8 984
我寻月下人不归
我寻月下人不归 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:27

    I suggest you to read the series of blog posts by Eric Lippert. The first part is Immutability in C# Part One: Kinds of Immutability. Very informative and helpful, as always. The series describes what does it mean for a variable to be readonly, immutable etc. in details.

    Generally, readonly means only that you can't re-assign a field outside the constructor. The field itself can be modified as long as it stays the same instance. So yes, you can add elements to the collection stored in readonly field.

    About mutability, this is more complex and it depends a bit what kind of mutability you consider. When Metadata internal values are references and those references itself (the instances it point to) doesn't change, you could say Metadata stays not mutated. But it is mutated logically. See Eric's posts for more insights.

提交回复
热议问题