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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay