C# 9.0 Init-only Property
Wriju's Blog
Posted on November 13, 2020
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.
💖 💪 🙅 🚩
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.