It provides syntax to initialize members of an object. For more clearance which value is setting in which property it’s made by property initializers. Here is one disadvantage of it is it’s properties need to be settable, in C#9 replaced “set accessors” with “initaccessors” for properties and indexers. Property initializer syntax is used by callers to set these values in creation completed. Change state window is provided by init only setters. Change state window is closed when the phase is ending and also constrictor phase is closed after all initialization is complete with property initializes and with expressions.
Some records represent immutable data that is copied, other than updated over time. It is grate to built-in data type immutable but now the problem is how we instantiate object? For that init-only property came.
The init-only is set o nly when the object is initialized and its syntax is just written “init” word add as modifier we add.
Now see how can you declare init, before it you need to declare it only setters in any type you write. Below is small code snippet to understand easily.
public structStudentAdmition
{
public DateTimeAdmitionDate{ get; init; }
public decimal ScoreInPr{ get; init; }
public decimal ScoreInPersentage{ get; init; }
public override string ToString() =>
$"Ad={ AdmitionDatett} on {AdmitionDate:M/d/yyyy}: " +
}
Callers have used property initializer syntax for set values when we still preserving the immutability:
Below is showing a small part of the code example to understand in an easy way.
var now = new StudentAdmition
{
AdmitionDate= DateTime.Now,
ScoreInPr= 78.7,
ScoreInPersentage = 68.0
};
By changing an observation after initialization is shown an error for assigning to an init-only property outside of initialization:
// Error! CS8852.
now.ScoreInPr = 78.7
This Init only setters are useful for set base class properties from derived classes. It also set derived properties using helpers in the base class. You can declare init-only setters for any struct and class which you want.
Init-only is a powerful feature of c#9. It allows you to create immutable properties without creating a constructor that takes the initial property values. You can also set the init-only property with an object initializer, and after that, you can't change itas they are immutable. It is very useful if you plan to work with immutable data in C#.