What does init mean in c# 9?

Viewed 2778

I have come across with "init" keyword in c# in the C# 9 preview. What does it mean and what are its applications?

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)));
    }
}
2 Answers

The init keyword creates so called Init Only Setters. They add the concept of init only properties and indexers to C#. These properties and indexers can be set at the point of object creation but become effectively get only once object creation has completed.

The main reason for the introduction is to avoid boilerplate code.

A simple immutable object like Point requires:

struct Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }
}

The init accessor makes immutable objects more flexible by allowing the caller to mutate the members during the act of construction. That means the object's immutable properties can participate in object initializers and thus removes the need for all constructor boilerplate in the type. The Point type is now simply:

struct Point
{
    public int X { get; init; }
    public int Y { get; init; }
}

The consumer can then use object initializers to create the object

var p = new Point() { X = 42, Y = 13 };

You can read the proposal with more details and explanation here:

https://github.com/dotnet/csharplang/blob/c2df2ee72f4b36fca2e07c701a90a0dba8d1fc20/proposals/init.md

The init is like the old 'set' but you are only allowed to use it on creation/initialization of the class.

Like:

var p = new Person { FirstName = "Adam", LastName = "West" };

After that you are not allowed to change FirstName or LastName.

This will throw an expection:

var p = new Person();
p.FirstName = "Adam";
Related