This is a new feature of c# 2.0. The null coalescing operator is a shortcut for checking if a value is null and, if so, returning the value of the second operand—kind of like an IIF. The syntax is as follows.
After the end of the article, you will be able to answer the following question.
- What is a null coalescing operator?
- When to use null coalescing operator in c#
As per the Microsoft Nullable
type is
void Main()
{
int? someValue = null;
if (someValue == null){
//DO SOMETHING
}
else{
Console.WriteLine(someValue.Value);
}
}
Let’s write the same code using C# null coalescing operator.
var result = someValue ?? default;
Console.WriteLine(result);
As you can see, the first syntax is very verbose while the null coalescing operator is clean.
You could also use this inline:
Console.WriteLine("The value is " + (someValue ?? "null"));
another use
return (bool)(ViewState["IsPaged"] ?? true);