DEV Community

Cover image for C# - Init-Only Setters for Immutable Properties
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Init-Only Setters for Immutable Properties

C# has init-only setters, which provide a more concise and expressive way to create immutable properties. They are particularly useful when creating objects with properties that can only be set during object initialization and remain immutable afterward.

Here’s how you can use init-only setters:

  1. Declare Properties with init Accessor:
    Use the init keyword instead of set for properties. This makes the property writable only at the time of object initialization.

  2. Object Initialization with Object Initializers:
    You can still use object initializers, but the properties become read-only after the object is fully constructed.

Example:

public class Product
{
    public string Name { get; init; }
    public decimal Price { get; init; }
}

public static void Main()
{
    var product = new Product
    {
        Name = "Coffee Mug",
        Price = 9.99M
    };

    // product.Name = "Tea Cup"; // This line would cause a compile-time error

    Console.WriteLine($"Product: {product.Name}, Price: {product.Price}");
}
Enter fullscreen mode Exit fullscreen mode

Init-only setters are a great way to ensure immutability in your objects, enhancing the robustness and predictability of your code. This feature is especially useful for data models in applications where immutability is desired, such as in multi-threaded scenarios or when working with data transfer objects in web applications.

Top comments (0)