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:
Declare Properties with
init
Accessor:
Use theinit
keyword instead ofset
for properties. This makes the property writable only at the time of object initialization.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}");
}
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)