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

Init-only setters in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Init-only setters let you set a property only when creating an object. After that, the property cannot change. This helps keep data safe and clear.

When you want to create objects with fixed values that should not change later.
When you want to make your code easier to understand by preventing accidental changes.
When you want to use immutable objects but still set properties easily during creation.
Syntax
C Sharp (C#)
public class Person
{
    public string Name { get; init; }
    public int Age { get; init; }
}

The init keyword allows setting the property only during object creation.

After the object is created, trying to change the property will cause a compile error.

Examples
Set properties when creating the object using object initializer syntax.
C Sharp (C#)
var person = new Person { Name = "Alice", Age = 30 };
You cannot change the property after the object is created.
C Sharp (C#)
person.Name = "Bob"; // This will cause a compile error
Init-only setters also work well with records for immutable data.
C Sharp (C#)
public record Car
{
    public string Model { get; init; }
    public int Year { get; init; }
}
Sample Program

This program creates a Person object with init-only properties. It prints the values. Trying to change Age after creation is not allowed.

C Sharp (C#)
using System;

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 };
        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        // person.Age = 31; // This line would cause a compile error
    }
}
OutputSuccess
Important Notes

Init-only setters were introduced in C# 9.0.

You can only set init-only properties during object initialization or in the constructor.

Summary

Init-only setters let you set properties only when creating an object.

They help make objects immutable after creation.

Trying to change an init-only property later causes a compile error.