Null Coalescing Operator (??) in C#
C Sharp What

Null Coalescing Operator (??) in C#

Editorial Team
Mishel Shaji
Editorial Team, Mishel Shaji

The Null Coalescing Operator (??) in C sharp is used to check for null values. It is a binary operator. If the value is null, the null coalescing operator returns the left operand and otherwise, it returns the right operand.

Here's an example.

int? i = null;
var res = i ?? 100;

// Displays 100
Console.WriteLine(res); 

Using Null Coalescing 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:

string name = null;
var res = string.Empty;

// Using If Else
if (name is null)
	res = "John Doe";
else
	res = name;

Example with ternary operator:

string name = null;
var res = string.Empty;
res = name is null ? "John Doe" : name;

Example with Null coalescing operator:

string name = null;
var res = string.Empty;
res = name ?? "John Doe";

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;
var res = i ?? 100; // Error
Console.WriteLine(res);

Using the null coalescing operator makes the code much more readable and easy to understand.



Join the conversation.