Skip to content

Init-only setters C# 9.0correctnessreadability

Specify properties that can only be set during construction.

Read-only properties are great for encapsulation but must be set by constructors and can't be used with object initializers.

Init-only setters allow you to specify properties that can only be set either by constructors or by using the object initializer C# 3.0 syntax.

Code

C#
class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}
C#
class Person
{
    public string FirstName { get; private; }
    public string LastName { get; private; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

More information