The Null-Coalescing Operator in C#

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

A nullable value type T? represents all values of its underlying value type T and an additional null value.{alertSuccess}

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.

(ads)
var result = someValue ?? default;
Console.WriteLine(result);

As you can see, the first syntax is very verbose while the null coalescing operator is clean.

The first operand someValue must be a nullable type. The above code will set the value of newValue to someValue unless it’s null, then it’ll set it to default.{alertInfo}

You could also use this inline:

Console.WriteLine("The value is " + (someValue ?? "null"));

another use

return (bool)(ViewState["IsPaged"] ?? true);

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post