Friday, January 15, 2021

C# 9.0: Fit and Finish

In some respects C# 3.0's var keyword is the foil to C# 9.0's fit and finish feature. Microsoft's overview of C# 9.0 features (What's new in C# 9.0) defines fit and finish as:

With the var keyword, the type of a variable is known based on the type assigned such as the following where the type is DateTime:

var lastTime = new DateTime(2020, 13, 31, 23, 59, 59);

C# 9.0's fit and finish removes the need for the type associated with the new keyword as the declaration makes this known:

DateTime valentinesDay = new(2021, 2, 14, 12, 0, 0);

Fit and finish can be used in field initialization (see line 11, 13, and 15):


Fit and finish can be used in conjunction with init only setters. To demonstrate consider the following class:


An instance of the Employee class can be instantiated as follows using fit and finish:

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


No comments :

Post a Comment