init (C# Reference)

In C# 9 and later, the init keyword defines an accessor method in a property or indexer. An init-only setter assigns a value to the property or the indexer element only during object construction. For more information and examples, see Properties, Auto-Implemented Properties, and Indexers.

The following example defines both a get and an init accessor for a property named Seconds. It uses a private field named _seconds to back the property value.

class InitExample
{
     private double _seconds;

     public double Seconds
     {
         get { return _seconds; }
         init { _seconds = value; }
     }
}

Often, the init accessor consists of a single statement that assigns a value, as it did in the previous example. You can implement the init accessor as an expression-bodied member. The following example implements both the get and the init accessors as expression-bodied members.

class InitExampleExpressionBodied
{
    private double _seconds;

    public double Seconds
    {
        get => _seconds;
        init => _seconds = value;
    }
}

For simple cases in which a property's get and init accessors perform no other operation than setting or retrieving a value in a private backing field, you can take advantage of the C# compiler's support for auto-implemented properties. The following example implements Hours as an auto-implemented property.

class InitExampleAutoProperty
{
    public double Hours { get; init; }
}

C# language specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also