0
0
CsharpConceptBeginner · 3 min read

What is init keyword in C#: Explanation and Usage

The init keyword in C# allows properties to be set only during object initialization, making them immutable afterward. It provides a way to create objects with read-only properties that can be assigned values using object initializers but not changed later.
⚙️

How It Works

The init keyword is like a special lock on a property that lets you set its value only once, right when you create the object. Imagine buying a new phone and setting your wallpaper and ringtone only during setup; after that, you can't change those settings. Similarly, with init, you can assign values to properties when you create an object, but once the object is ready, those properties become read-only.

This feature helps keep objects safe from accidental changes after they are created, which is useful when you want to make your data more reliable and predictable. It works by allowing property setters to be called only during the object's initialization phase, such as inside an object initializer or constructor, but not afterward.

💻

Example

This example shows a class with an init property. You can set the property when creating the object, but trying to change it later causes a compile error.

csharp
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}");
    }
}
Output
Name: Alice, Age: 30
🎯

When to Use

Use the init keyword when you want to create objects that should not change after they are set up. This is especially helpful for immutable data models, configuration settings, or value objects where consistency is important.

For example, in applications where you pass data between parts of a program or across networks, using init properties ensures that once data is created, it cannot be accidentally modified, reducing bugs and making your code easier to understand and maintain.

Key Points

  • init allows setting properties only during object creation.
  • After initialization, properties become read-only.
  • Helps create immutable objects with simpler syntax than readonly fields.
  • Introduced in C# 9.0 to improve safety and clarity in object initialization.

Key Takeaways

The init keyword makes properties settable only during object initialization.
It helps create immutable objects that cannot be changed after creation.
Use init for safer and clearer data models and configuration objects.
Trying to set an init property after initialization causes a compile error.
Init was introduced in C# 9.0 to improve object immutability support.