Null Coalescing Assignment Operator in C Sharp
C Sharp Code Snippet What

Null Coalescing Assignment Operator in C Sharp

Mishel Shaji
Mishel Shaji

The Null Coalescing Assignment Operator (??=) in C sharp is used to set a default value to a variable if the value is null. This operator is similar to the Null Coalescing Operator.

💡
The null coalescing assignment operator assigns the value of the right operand to the left operand if the value of the left operand is null.

Here's an example.

int? i = null;
i ??= 0;
Console.WriteLine(i);

In this example, the value of I is null. In the next line, we are using the null coalescing assignment operator to set a default value 0 to the variable i if its value is null.

💡
The null coalescing assignment operator is available only in C sharp version 8 and later.

Using Null Coalescing Assignment Operator

With the null coalescing operator we can avoid the use of if-else statements to set a default value if a variable is null.

Example with if-else:

int? age = null;

// Using If
if (age is null)
    age = 15;

Console.WriteLine($"The age is {age}");

Example with Null coalescing assignment operator:

int? age = null;

// The age will get the value 15 if age is null.
age = age ??= 15;

// The answer is 15 because age was null.
Console.WriteLine($"The age is {age}");

Using with value types

The left operand of the null coalescing operator should be either a nullable type or a reference type. We cannot use a value type as the left operand.

// The left operand (i) should not be a value type
int i = 10;
i ??= 100; // Error
Console.WriteLine(res);

With the null coalescing assignment operator, we can set a default value for a variable if its value is null without using the if statements.