?? 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.
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: