Introduction
In this article, I am going to explain Init-only setter property which has been introduced in C# 9.0.
Each C# release has its own features. In C# 9.0, many new wonderful features have been added and here we are going to discuss important feature Init-only setter property.
Before we start, we should have basic understanding of immutable and mutable in c#.
What’s meaning of Mutable and Immutable in English?
Answers are.
- Mutable: Can change
- Immutable: Cannot Change
In simple words we can say, immutable means object cannot be changed once it is created. If you want to change, you have to create new object/ assign new memory. Example of immutable type is string in C#.
What is Init-only setter property?
Before we start with Init-only property, we have to understand the traditional way of working (properties).
Let’s start with an example.
Suppose, we have Member class which has 3 properties.
- ID: Member unique ID
- Name: Member Name
- Address: Member Address
public class Member { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } }
Now create object of Member class and assign some values.
using System;
namespace C_9._0
{
class Program
{
static void Main(string[] args)
{
Member memberObj = new Member();
memberObj.Id= 1;
memberObj.Name="Kirtesh Shah";
memberObj.Address="Vadodara";
Console.WriteLine("****************START - Member Details***********");
Console.WriteLine("ID : -" + memberObj.Id);
Console.WriteLine("Name :- " + memberObj.Name);
Console.WriteLine("Address:- " + memberObj.Address);
Console.ReadLine();
Console.WriteLine("****************END - Member Details***********");
}
}
}
All looks good right? But what happens if someone changed Member ID? ID is unique and it should not be editable, which means it should be immutable, not mutable. That's the problem with the traditional way, properties are mutable.
If we want to make properties immutable in the traditional way, we have to pass values in constructor like the below code.
public class Member
{
public Member(int memberId)
{
Id = memberId;
}
public int Id { get; }
public string Name { get; set; }
public string Address { get; set; }
}
ID property is immutable now.
Let's see the below code.



Mark KanePosted Dec 13, 2023, 12:57 AM
Nice article. Please give an example of "Init-only property has the capability to set read only property to implement validations."
Yogesh SPosted Jan 2, 2023, 6:50 AM
Learned a lot !! Thank you ..!
Arjunan SelvamPosted Jun 25, 2021, 3:10 PM
Looks like Constructor is missing in c# 9.0 examples.