Introduction
In today’s article, we will look at Init-only properties how they work and what are the advantages of having them. This is a new feature in C# 9.0.
What are Init-only properties?
Microsoft recently announced the availability of .NET 5 release candidate at Microsoft Ignite 2020. This included the latest features in C# 9.0. In order to code in .NET 5.0, we would need to install the latest preview of Visual Studio 2019 (Version 16.8.0 Preview 3.1). As I had read about some cool features in C# 9.0including Init-only properties, I downloaded and installed the required version as below.

We have all created immutable classes in previous versions of C#. The way to set values of properties in these immutable classes is by passing values via the constructor.
This is where Init-only properties come in. By using them, we can set values at the time of creating the class instance. However, this is the only time we can set these values.
After that, we are not allowed to change the values. Hence, the class is immutable without us having to create a constructor just to set the values of the properties.
Using Init-only properties
Let us see them in action.
Let us create a console application in Visual Studio 2019 (Version 16.8.0 Preview 3.1) as below.



Let us look at the properties of the project. These are as below.

Now, we enter the below code
using System;
namespace ConsoleAppInit
{
class Program
{
static void Main(string[] args)
{
var employee = new Employee(1, "John Smith", 30);
Console.Write($"Employee details: Id={employee.ID}, Name={employee.Name}, Age={employee.Age}");
Console.ReadKey();
}
}
public class Employee
{
public int ID
{
get;
private set;
}
public string Name
{
get;
private set;
}
public int Age
{
get;
private set;
}
public Employee() { }
public Employee(int id, string name, int age)
{
ID = id;
Name = name;
Age = age;
}
}
}






Join the conversation! Your thoughts help the community grow.