Understanding Init-only setters
In C#, we use object initializers, which were introduced in C# 7.0, to set the values of properties by making them settable. But if we wish to have them set only during object initialization, we need to write a lot of boilerplate code. In C# 9.0, with init-only setters, can let the property be initialized during object creation. Init-only setters can be declared for any class or struct.
The following code snippet defines the Order
class with OrderId
as an init-only setter. This enforces OrderId
to be initialized only during object creation:
public class Order { Â Â Â Â Â Â Â Â public int OrderId { get; init; } Â Â Â Â Â Â Â Â public decimal TotalPrice { get; set; } }
We can instantiate the Order
class and initialize OrderId
at the time of object creation, as shown in the following code snippet:
class Program { Â Â Â Â static void Main(string[] args) Â Â ...