Null-coalescing Operator in C# - freeCodeCamp Guides

I’ve been coding with Microsoft technologies for a long, long time. I’ve been a .NET C# developer since the beginning. I am also proud and humbled to say I was a Microsoft MVP in C# for many years.

I noticed the freeCodeCamp Guides had very little content in C# at one point so I added a section on the Null-coalescing Operator.

Null-coalescing Operator

The null-coalescing operator in C# is used to help assign one variable to another and specify an alternate value if the source value is null. The null-coalescing operator in C# is ??.

Example 1

Since name is null, clientName will be assigned the value “John Doe”.

string name = null;

string clientName = name ?? "John Doe";

Console.WriteLine(clientName);

> John Doe

Example 2

Since name is not null, clientName will be assigned the value of name, which is “Jane Smith”.

string name = "Jane Smith";

string clientName = name ?? "John Doe";

Console.WriteLine(clientName);

> Jane Smith

Alternative to if…else Statement

You could use an if...else statement to test for the presence of null and assign a different value.

string clientName;

if (name != null)
    clientName = name;
else
    clientName = "John Doe";

However, this can be greatly simplified using the null-coalescing operator.

string clientName = name ?? "John Doe";

Alternative to Conditional (Ternary) Operator

It is also possible to use the conditional operator to test for the presence of null and assign a different value.

string clientName = name != null ? name : "John Doe";

Again, this can be simplified using the null-coalescing operator.

string clientName = name ?? "John Doe";

References

Contents