Categories
Coding

C# 9 init

I really like the looking of what’s coming in C# 9. My favourite features so far scratches an itch that previously just wouldn’t go away. When creating a class with readonly properties prior to C# 9 you had to write something like this…

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

    public string FirstName { get; }
    public string LastName { get; }
}

… which is fine in as far as it goes but you can’t use the object initializer syntax…

var p = new Person{ FirstName = "Russell", LastName = "Gilbert"}

C# 9 fixes this with the init accessor. Now my class looks like this…

public class Person
{
    public string FirstName { get; init;}
    public string LastName { get; init;}
}

… and works fine with the initializer syntax.

Because init accessors can only be used during initialization, meaning the properties are still immutable, they are allowed to set read only fields, so this is fine too…

public class Person
{
    private readonly string firstName;

    public string FirstName
    {
        get => firstName;
        init => value;
    }
}

This small change feels like a really useful addition to the C# armoury.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.