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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…