What if you could set a property once and be sure it never changes by mistake?
Why Init-only setters in C Sharp (C#)? - Purpose & Use Cases
Imagine you want to create a person record in your program and set their name and age. You write code that sets these values one by one after creating the person object.
Later, you realize you want to make sure these values never change once set, but your code allows changes anywhere, causing bugs.
Manually preventing changes after setting values means extra code everywhere to check if a value can be changed.
This is slow, error-prone, and makes your code messy and hard to maintain.
Init-only setters let you set properties only once during object creation.
After that, the properties become read-only automatically, so you don't need extra checks.
This keeps your code clean and safe from accidental changes.
var person = new Person(); person.Name = "Alice"; person.Age = 30; // Later someone changes person.Name = "Bob"; // no restriction
var person = new Person { Name = "Alice", Age = 30 };
// person.Name = "Bob"; // error: cannot change after initYou can create objects with properties that are set once and then stay fixed, making your programs more reliable and easier to understand.
When creating a configuration object for an app, you want to set values once at startup and never change them accidentally during runtime.
Init-only setters allow setting properties only during object creation.
This prevents accidental changes later, reducing bugs.
It makes your code cleaner and safer without extra checks.