Skip to main content
purpose of ?? operator in C#

What is the purpose of ?? operator in C#?

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise, it returns the right-hand operand.

You might already know that C# 2.0 provides us Nullable Types which can be used to store null values for value type variables such as int, float, decimal etc.

For example, let’s consider the following code snippet.

int? x = null;            
int y = x ?? 0;
Console.WriteLine(y);

In the above example, x is a nullable int and if you assign it to the non-nullable int y then it will throw a runtime exception if x is null.

Purpose of ?? operator in C#

Well, ?? provides a convenient way to assign a nullable type to a non-nullable type.

 int y = x ?? 0; 

It saves us having to write code that tests for null and sets a value appropriately. The above statement sets the value of ‘y’ to the value of ‘x’ unless the value in ‘x’ is null, in which case it sets it to 0.


if (x == null)
    y = 0;
else
    y = x;

In other words ?? is a short form of the above test.

The result of a ?? operator is not considered to be constant even if both its arguments are constants.

Hope you like this article. Happy coding!

Few recommended posts you would love to read:

DotNetCrunch

DotNetCrunch is a popular blog for latest Microsoft® technologies which is aimed for beginners and intermediate level professionals.