How to create immutable objects in C#?

后端 未结 8 488
有刺的猬
有刺的猬 2020-12-23 20:26

In a question about Best practices for C# pattern validation, the highest voted answer says:

I tend to perform all of my validation in the constructor

8条回答
  •  忘掉有多难
    2020-12-23 21:24

    Declaring all fields readonly is a good step towards creating an immutable object, but this alone is not sufficient. This is because a readonly field can still be a reference to a mutable object.

    In C# immutability is not enforced by the compiler. You just have to be careful.

提交回复
热议问题