I have come across with "init" keyword in c# in the C# 9 preview. What does it mean and what are its applications?
public class Person
{
private readonly string firstName;
private readonly string lastName;
public string FirstName
{
get => firstName;
init => firstName = (value ?? throw new ArgumentNullException(nameof(FirstName)));
}
public string LastName
{
get => lastName;
init => lastName = (value ?? throw new ArgumentNullException(nameof(LastName)));
}
}
The INIT function initializes the data structures required by the rest of the computation of the aggregate. For example, if you write a C function, the INIT function can set up large objects or temporary files for storing intermediate results.
1. Abbreviation for initialization or initialize. 2. When referring to Linux or Unix, init is a program loaded by the kernel that spawns all other processes and often uses PID 1.
Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.
Initializing variables in C means allocating values to variables directly while declaring it. The syntax for initializing variables are as follows: data_type variable_name = value; For example.
The init keyword creates so called Init Only Setters. They add the concept of init only properties and indexers to C#. These properties and indexers can be set at the point of object creation but become effectively get only once object creation has completed.
The main reason for the introduction is to avoid boilerplate code.
A simple immutable object like Point requires:
struct Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
}
The init accessor makes immutable objects more flexible by allowing the caller to mutate the members during the act of construction. That means the object's immutable properties can participate in object initializers and thus removes the need for all constructor boilerplate in the type. The Point type is now simply:
struct Point
{
public int X { get; init; }
public int Y { get; init; }
}
The consumer can then use object initializers to create the object
var p = new Point() { X = 42, Y = 13 };
You can read the proposal with more details and explanation here:
https://github.com/dotnet/csharplang/blob/c2df2ee72f4b36fca2e07c701a90a0dba8d1fc20/proposals/init.md
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With