How to create immutable objects in C#?

后端 未结 8 474
有刺的猬
有刺的猬 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:03

    C# 9 is coming up with new feature names as Record. Init-only properties are great if you want to make individual properties immutable. If you want the whole object to be immutable and behave like a value, then you should consider declaring it as a record:

    public data class Person
    {
        public string FirstName { get; init; }
        public string LastName { get; init; }
    }
    

    The data keyword on the class declaration marks it as a record.

    Reference: https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#records

提交回复
热议问题