Init. Suppose you have a property on a class that must be always set. For example, a Bird must always have a color. And you want to disallow setting it later or changing it.
With the init keyword, we can require that an initializer sets a property, so it is always set. We cannot use the set keyword alongside init, as this is redundant.
Example. Consider a Bird class that has a Color, and our requirement is that each Bird must always have a Color set. We specify init on the Color string property.
Next In the Main method, we create an instance of the Bird class and specify an initializer that assigns Color in the same statement.
using System;
class Bird
{
public string Color { get; init; }
}
class Program
{
static void Main()
{
// Use the init property.
var bird = new Bird() { Color = "Blue" };
Console.WriteLine(bird.Color);
}
}Blue
Init error. The init keyword is unlike the set keyword in that it prohibits assigning the property later, after initialization. The C# compiler will issue an error in this case.
using System;
class Bird
{
public string Color { get; init; }
}
class Program
{
static void Main()
{
// With an init property, we must use an initializer.
var bird = new Bird();
bird.Color = "orange";
}
}... Program.cs(14,9): error CS8852:
Init-only property or indexer 'Bird.Color' can only be assigned in an object initializer,
or on 'this' or 'base ' in an instance constructor or an 'init' accessor.
...
Summary. We init, we have a keyword that acts like "set" but adds a constraint that the property must be set at initialization-time only. This can reduce incorrect usage of a property.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.