C# - What is the init keyword for properties?

You may have encountered the init accessor on a property in the wild and now you are wondering what it does. Does it do what you think it does? yes it does. Here is an example:

public class Person {
    public string FirstName { get; init; } //note init
    public string LastName { get; set; }
}

In the above the access level of our properties are public but instead of using the set accessor for FirstName we are using the init accessor. With a public set accessor you can set the value of the property anytime you can access the object. If it uses init, you can only set the value upon the object being instantiated. Once this is set you cannot change it later and it is therefore immutable. We can use the following example:

var person = new Person
{
    FirstName = "Peter",
    LastName = "Rasmussen"
};

person.FirstName = "Peter"; // Not allowed
person.LastName = "Daugaard"; // Allowed

In the above we are only allowed to change the LastName property, but not the FirstName property. It gives you a compile time error if you try: "CS8852 Init-only property or indexer 'Person.FirstName' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor."

Just like with the other set accessors you do not have to provide a value and you can set a default value.

An alternative to the init accessor is a private set with a constructor, however when doing this the value can still be changed privately inside the class after having been instantiated.

I hope you found this helpful!