0
0
C Sharp (C#)programming~3 mins

Why Init-only setters in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could set a property once and be sure it never changes by mistake?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
var person = new Person();
person.Name = "Alice";
person.Age = 30;
// Later someone changes person.Name = "Bob"; // no restriction
After
var person = new Person { Name = "Alice", Age = 30 };
// person.Name = "Bob"; // error: cannot change after init
What It Enables

You can create objects with properties that are set once and then stay fixed, making your programs more reliable and easier to understand.

Real Life Example

When creating a configuration object for an app, you want to set values once at startup and never change them accidentally during runtime.

Key Takeaways

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.