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; }
}
var book = new Book { Title = "Indian Birds", Author = "Salim Ali" };
Console.WriteLine("{0} - {1}", book.Title, book.Author);
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);
}
var book = new Book("Indian Birds","Salim Ali");
By using init
only you can achieve it easily
public class Book
{
public string Title { get; init; }
public string Author { get; init; }
}
var book = new Book { Title = "Indian Birds", Author = "Salim Ali" };
This becomes both readonly and parameterized constructor-less class.
I love this.
Top comments (1)
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.