Sunday 7 September 2008

The C# ?? (null coalescing) operator

The ?? operator checks whether the value on the left side of the expression is null, and if so it returns an alternate value on the right side of the expression. If the value on the left side of the expression isn't null, it returns the original value.

Example 1:
string input = null;
string output = input ?? "Input is null";

// Outcome: ouput == "Input is null".


Example 2:
string input = "Hello World";
string output = input ?? "Input is null";

// Outcome: ouput == "Hello World".

No comments: