DEV Community

Wriju's Blog
Wriju's Blog

Posted on

C# 9.0 Init-only Property

This init-only property solves a very unique problem of C#. Imagine you have a property which you want to make readonly then you can't have set defined in it to avoid setting it. Instead you need a parametrized constructor to set the value while initializing. If you want to have both a property readonly and no constructor, then this init-only solves both the problems elegantly.

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
var book = new Book { Title = "Indian Birds", Author = "Salim Ali" };

Console.WriteLine("{0} - {1}",  book.Title, book.Author);
Enter fullscreen mode Exit fullscreen mode

If you mark the properties readonly by removing setter then you need a parameterized constructor.

public class Book
{
    public string Title { get;  }
    public string Author { get; }

    public Book(string _title, string _author) =>
        (this.Title, this.Author) = (_title, _author);
}
Enter fullscreen mode Exit fullscreen mode
var book = new Book("Indian Birds","Salim Ali");
Enter fullscreen mode Exit fullscreen mode

By using init only you can achieve it easily

public class Book
{
    public string Title { get; init; }
    public string Author { get; init; }    
}
Enter fullscreen mode Exit fullscreen mode
var book = new Book { Title = "Indian Birds", Author = "Salim Ali" };
Enter fullscreen mode Exit fullscreen mode

This becomes both readonly and parameterized constructor-less class.

I love this.

Discussion (1)

Collapse
portlandtn profile image
Jedidiah May

This and the new Records were the most intriguing things that popped out from the dotnet conference for me on C# 9. Don't get me wrong, excited about the other stuff, but these are the two that stand out in my mind when I remember the C# 9 features coming.