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.
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.
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
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. ...
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.