C# 8.0 introduces the null-coalescing assignment operator ??=. You can use the ??= operator to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. In C# 7.3 the null-coalescing operator ?? also had a few requirements that are now required in C# 8.0. We will discuss this also in detail.
Prerequisites
Let's Start
Use null-coalescing assignment operator ??= to assign the value of right-hand side operand to left-hand side operand only if the left-hand side operand evaluates to null.
For instance, in the below-given code, I'm initializing a List of int named "numbers" with the null reference. Then I'm using Null-coalescing assignment operator to assign a new List of int if "numbers" value is null.
- List<int> numbers = null;
- int? a = null;
-
- (numbers ??= new List<int>()).Add(5);
- Console.WriteLine(string.Join(" ", numbers));
-
- numbers.Add(a ??= 0);
- Console.WriteLine(string.Join(" ", numbers));
- Console.WriteLine(a);
In previous versions of C# like 7.3 we were using other different techniques to do the same task as performed by Null-coalescing assignment operator??. For instance, I'm using Null-coalescing operator to do the same but it seems a little bit cheap.
- List<int> numbers = null;
- int? a = null;
-
- (numbers = numbers ?? new List<int>()).Add(5);
- Console.WriteLine(string.Join(" ", numbers));
-
- numbers.Add((a=a??0).Value);
- Console.WriteLine(string.Join(" ", numbers));
- Console.WriteLine(a);
Null-coalescing operator updated requirements
In C# 7.3 and earlier, the type of the left-hand operand of the ?? operator must be either a reference type or a
nullable value type. Beginning with C# 8.0, that requirement is replaced with the following: the type of the left-hand operand of the ?? and ??= operators cannot be a non-nullable value type. For instance:
- int? number = null;
- number =number?? 0;
In particular, beginning with C# 8.0, you can use the null-coalescing operators with unconstrained type parameters. For instance, I'm using Null-coalescing operator with non-nullable type and it gives the error.
- int number = 5;
- number = number ?? 0;
So when I tried to build this. It gives an error:
ErrorCS0019Operator '??' cannot be applied to operands of type 'int' and 'int'
For more new features of C# 8.0, please see
MS Docs.