C# 9 Init-Only Properties, despite the name, will allow the initializer syntax to be able to set readonly fields as well.
Here are the relevant parts copied from the links.
Init-only properties
Here's a simple example of object initializer.
new Person
{
FirstName = "Scott",
LastName = "Hunter"
}
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.
Init accessors and readonly fields
Because init
accessors can only be called during initialization, they are allowed to mutate readonly
fields of the enclosing class, just like you can in a constructor.
public class Person
{
private readonly string firstName;
private readonly string lastName;
public string FirstName
{
get => firstName;
init => firstName = (value ?? throw new ArgumentNullException(nameof(FirstName)));
}
public string LastName
{
get => lastName;
init => lastName = (value ?? throw new ArgumentNullException(nameof(LastName)));
}
}