Init only setters in C# 9.0 provide a method to initialize object members.
C# 9.0 allows the user to create init
accessors instead of set
accessors. init
accessors allow the members of an instance of the object to be set only at the time of the construction. Once the construction of the instance is complete, the members become immutable.
However, the set
accessor allows the members to be changed even after the initialization is complete.
init
can be declared on members of any object and callers can use property initializers to set the members at the time of the creation of an object.
The following example demonstrates how to use init
only setters.
Student
, and declares two of its members with init
and the third member lastName
with set
.set
accessor.using System;namespace c9 {// create an objectpublic class Student {// replace set with initpublic int Id {get; init;}public string firstName { get;init;}public string lastName { get;set;}}class Program {static void Main(string[] args) {Student studentOne = new Student{Id = 1, firstName = "Sam"};// set the last name after initializationstudentOne.lastName = "Carlos";//display propertiesConsole.WriteLine("ID : " + studentOne.Id);Console.WriteLine("Name : " + studentOne.firstName);Console.WriteLine("Last Name : " + studentOne.lastName);}}}
ID : 1
Name : Sam
Last Name : Carlos
Free Resources