Skip to main content

?? and ??= Null coalescence operators C#

· 2 min read
Ragavendra Nagraj

C# introduces the ?? and ??= operators which are known as the Null coalescence operators.

Purpose - The ?? and ??= operators can help in cases where a comparison is made between two or more variable values and depending on the order in the statement, the variable valu is used.

Say for example there is variable either a and b to be returned by a method. Say if value is needed to be returned if it is not null and if yes, the value b is supposed to be returned.

public class NullCoal
{
public static int? Method(int? input)
{
....
....
int? a;
int? b;


if(input > 10)
{
a = input * 6;
}
else
{
b = input * 7:;
}

return a ?? b;
}
}

In the above example, a is returned if it is not null or b is returned.

Similarly the ??= operator adds the assignment operation as well, which can be used like

    int? a = null;
int? b = 1;

a ??= b;

where if a is not null, value of b is assigned to it, otherwise nothing happens with the above statement.

The null coalescence operator is a short form for writing the below code.

if( a is null)
{
a = 1;
}

instead it can be written as

a ??= 1;

What if there is more than two variables to check, in such cases say like below

return a ?? b ?? c;

the expression is evaluated from right to left like this

return a ?? ( b ?? c)