How to create immutable objects in C#?

后端 未结 8 422
有刺的猬
有刺的猬 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.

    0 讨论(0)
  • 2020-12-23 21:29

    An immutable value object is a value object that cannot be changed. You cannot modify its state, you have to create new ones

    Check out Eric Lippert's blog:

    Kinds of Immutability https://docs.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability

    Have a look at

    Immutable object pattern in C# - what do you think?

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