What does immutable and readonly mean in C#?

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

    There is nothing preventing you from mutating an object stored in a readonly field. So you CAN call _items.Add() and metadata._Change() outside the constructor/initializer. readonly only prevents you from assigning new values to those fields after construction.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题