C# 9.0 Init-only Property

wrijugh

Wriju's Blog

Posted on November 13, 2020

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.

💖 💪 🙅 🚩
wrijugh
Wriju's Blog

Posted on November 13, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

C# 9.0 Init-only Property
csharp C# 9.0 Init-only Property

November 13, 2020