This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
init
keyword (C# Reference)Theinit
keyword defines anaccessor method in a property or indexer. An init-only setter assigns a value to the property or the indexer elementonly during object construction. Aninit
enforces immutability, so that once the object is initialized, it can't be changed. Aninit
accessor enables calling code to use anobject initializer to set the initial value. As a contrast, anautomatically implemented property with only aget
setter must be initialized by calling a constructor. A property with aprivate set
accessor can be modified after construction, but only in the class.
The following code demonstrates aninit
accessor in an automatically implemented property:
class Person_InitExampleAutoProperty{ public int YearOfBirth { get; init; }}
You might need to implement one of the accessors to provide parameter validation. You can do that using thefield
keyword, introduced as a preview feature in C# 13. Thefield
keyword accesses the compiler synthesized backing field for that property. The following example shows a property where theinit
accessor validates the range of thevalue
parameter"
class Person_InitExampleFieldProperty{ public int YearOfBirth { get; init { field = (value <= DateTime.Now.Year) ? value : throw new ArgumentOutOfRangeException(nameof(value), "Year of birth can't be in the future"); } }}
Important
Thefield
keyword is a preview feature in C# 13. You must be using .NET 9 and set your<LangVersion>
element topreview
in your project file in order to use thefield
contextual keyword.
You should be careful using thefield
keyword feature in a class that has a field namedfield
. The newfield
keyword shadows a field namedfield
in the scope of a property accessor. You can either change the name of thefield
variable, or use the@
token to reference thefield
identifier as@field
. You can learn more by reading the feature specification forthefield
keyword.
Theinit
accessor can be used as an expression-bodied member. Example:
class Person_InitExampleExpressionBodied{ private int _yearOfBirth; public int YearOfBirth { get => _yearOfBirth; init => _yearOfBirth = value; }}
The following example defines both aget
and aninit
accessor for a property namedYearOfBirth
. It uses a private field named_yearOfBirth
to back the property value.
class Person_InitExample{ private int _yearOfBirth; public int YearOfBirth { get { return _yearOfBirth; } init { _yearOfBirth = value; } }}
Aninit
accessor doesn't force callers to set the property. Instead, it allows callers to use an object initializer while prohibiting later modification. You can add therequired
modifier to force callers to set a property. The following example shows aninit
only property with a nullable value type as its backing field. If a caller doesn't initialize theYearOfBirth
property, that property has the defaultnull
value:
class Person_InitExampleNullability{ private int? _yearOfBirth; public int? YearOfBirth { get => _yearOfBirth; init => _yearOfBirth = value; }}
To force callers to set an initial non-null value, you add therequired
modifier, as shown in the following example:
class Person_InitExampleNonNull{ private int _yearOfBirth; public required int YearOfBirth { get => _yearOfBirth; init => _yearOfBirth = value; }}
The following example shows the distinction between aprivate set
, read only, andinit
property. Both the private set version and the read only version require callers to use the added constructor to set the name property. Theprivate set
version allows a person to change their name after the instance is constructed. Theinit
version doesn't require a constructor. Callers can initialize the properties using an object initializer:
class PersonPrivateSet{ public string FirstName { get; private set; } public string LastName { get; private set; } public PersonPrivateSet(string first, string last) => (FirstName, LastName) = (first, last); public void ChangeName(string first, string last) => (FirstName, LastName) = (first, last);}class PersonReadOnly{ public string FirstName { get; } public string LastName { get; } public PersonReadOnly(string first, string last) => (FirstName, LastName) = (first, last);}class PersonInit{ public string FirstName { get; init; } public string LastName { get; init; }}
PersonPrivateSet personPrivateSet = new("Bill", "Gates");PersonReadOnly personReadOnly = new("Bill", "Gates");PersonInit personInit = new() { FirstName = "Bill", LastName = "Gates" };
For more information, see theC# Language Specification. The language specification is the definitive source for C# syntax and usage.
Was this page helpful?
Was this page helpful?