c# 9 introduces new Init-Only property that allow to make immutable properties in a class. This means the property with "init" keyword in place of "set" keyword allows the property to be initialized at the construction step of an object. it doesn't allow you to set the value later, once the object is initialised.
For example
public class Friend
{
public Friend(string name, string surname)
{
this.Name = name;
this.Surname = surname;
}
public string Name { get; init; }
public string Surname { get; init; }
}
Use of Friend
public void SomeMethod()
{
Friend friend = new Friend("John", "Sharma");
var newFriend = new Friend("Tom", "Pandey");
}
Use of init property after initialization throws an error. for eg.
public void SomeMethod()
{
Friend friend = new Friend("John", "Sharma");
var newFriend = new Friend("Tom", "Pandey");
friend.Surname = "xxx"; //<--- Error here.
}