What is difference between Init-Only and ReadOnly in C# 9?

丶灬走出姿态 提交于 2020-08-10 19:29:46

问题


I am going through C# 9 new features which will be released soon. Init-Only properties are being introduced with it.

The one big limitation today is that the properties have to be mutable for object initializers to work: They function by first calling the object’s constructor (the default, parameterless one in this case) and then assigning to the property setters.

Init-only properties fix that! They introduce an init accessor that is a variant of the set accessor which can only be called during object initialization:

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

With this declaration, the client code above is still legal, but any subsequent assignment to the FirstName and LastName properties is an error. What does this line mean? If ReadOnly also does the same thing then what is use of Init-Only property.


回答1:


As stated in the new C# 9 features post,

The one big limitation today is that the properties have to be mutable for object initializers to work: They function by first calling the object’s constructor (the default, parameterless one in this case) and then assigning to the property setters.

However, value types with readonly modifiers are immutable as stated in readonly documentation.

Therefore, it is not possible to use readonly properties with object initializers.

However, with Init-only properties you can use object initializers.



来源:https://stackoverflow.com/questions/62372422/what-is-difference-between-init-only-and-readonly-in-c-sharp-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!