Init Only Setter in C#: What It Is and How to Use It
init only setter in C# is a special kind of property setter that allows setting a property value only during object initialization. After the object is created, the property becomes read-only, preventing further changes. This feature helps create immutable objects with flexible initialization.How It Works
Think of an init only setter like setting the ingredients of a recipe only while you are cooking. Once the dish is ready, you cannot change the ingredients anymore. In C#, this means you can assign values to properties only when you create the object, either using an object initializer or in the constructor.
After the object is fully created, the properties with init setters become read-only, so you cannot accidentally change them later. This helps keep your objects safe and consistent, like sealing a box after packing it.
Example
This example shows a class with an init only setter. You can set the property when creating the object, but trying to change it later causes a compile error.
public class Person { public string Name { get; init; } public int Age { get; init; } } class Program { static void Main() { var person = new Person { Name = "Alice", Age = 30 }; // person.Name = "Bob"; // This line would cause a compile error System.Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } }
When to Use
Use init only setters when you want to create objects that should not change after creation but still want the convenience of setting properties with object initializers. This is common in data models, configuration settings, or any scenario where immutability improves safety and clarity.
For example, when you receive data from an API or database, you can create immutable objects that represent that data without worrying about accidental changes later in your program.
Key Points
- Init only setters allow property values to be set only during object creation.
- They help create immutable objects with flexible initialization.
- Trying to set the property after initialization causes a compile-time error.
- Introduced in C# 9.0, they improve code safety and readability.