Summary: in this tutorial, you’ll learn how to use the C# init keyword to declare a field that can be set during the object initialization.
Introduction to the C# init keyword #
Sometimes, you want to initialize an object and do not want to change it after that. In other words, you want the object to be immutable.
To do that you can use the init keyword to define an accessor method in a property or indexer of the object.
The init keyword will make the setter the init-only setter that assigns a value to the property or indexer only during object initialization.
The following example demonstrates how to use the init keyword in C#:
class Person
{
public string Name { get; init; } = string.Empty;
public sbyte Age { get; init; } = 1;
}In this example, we define the Person class with two properties Name and Age. Both properties use the init keyword. It means that you can only set their value during the object initialization like this:
var person = new Person()
{
Name = "John",
Age = 22
};If you attempt to assign a value to the init-only property, you’ll get a compiled time error. For example:
person.Name = "Jane"; // errorSummary #
- Use the
initkeyword to define an accessor method in a property or indexer that assigns a value to the property or indexer element only during object initialization.
Thank you for your feedback!