Thursday, January 14, 2021

C# 9.0: Init Only Setters

 C# 9.0 introduces init only setters which allow properties to be assigned when an object is constructed and after construction those properties are read-only. To understand how init only setters are beneficial consider the Employee class:


The Salary property (line 9) has a private setter which means to initialize this property a value must be passed to the constructor (line 5). Imagine a case where the Employee class had thirty properties with private setters. The constructor in this case would contain an unmanageable number of parameters. 

An example of an init only setter is Employee class' Salary property (line 18):


The Salary can be set at initialization such as:

var employee = new Employee { Name = "Joe", Salary = 100000 };

The Name property is public and can be assigned after initialization. The Salary property uses an init only setter which means it cannot be assigned after initiation.

No comments :

Post a Comment