CSharp 10 Features

Last Updated: 4/13/2022

Improved Definite Assignment

  • C# requires definite assignment which means variables must be initialized or assigned to before they are used.
  • Prior to C# 10, there were many scenarios where definite assignment and null state analysis produced compile errors in the following scenarios
    • Comparison to bool constant
    • Comparison between a conditional access and a constant value
    • Conditional access coalesced to a bool constant
    • Conditional expressions where one arm is a bool constant

The following code generates error

public class C
{
	public bool M(out object obj)
	{
		obj = new object();
		return true;
	}
}

C c = new C();
if (c != null && c.M(out object obj0))
{
    obj0.ToString(); // ok
}

if ((c != null && c.M(out object obj1)) == true)
{
    obj1.ToString(); // error use of unassigned local variable
}

if ((c != null && c.M(out object obj2)) is true)
{
    obj2.ToString(); // error use of unassigned local variable
}

if (c?.M(out object obj3) == true)
{
    obj3.ToString(); // error use of unassigned local variable
}

if (c?.M(out object obj4) ?? false)
{
    obj4.ToString(); // error use of unassigned local variable
}

definite-assignment-compile-error

C# 10 Improvements

From C# 10, these scenarios don't generate compile errors.

definite-assignment-compile-error

Example

References