Friday, 23 December 2011

The C# ?? null coalescing operator

The C# ?? operator provides a nice way to check whether a value is null, and if so return an alternate value.

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

string message = "Welcome";
string result = message ?? "Good Bye";
//outcome: result == "Welcome"

string message = null;
string result = message ?? "Good Bye";
//outcome: result == "Good Bye"

int? age = 21;
int result = age ?? 0;
//outcome: result == 21


int? age = null;
int result = age ?? 0;
//outcome: result == 0

Click here to read more.

No comments:

Post a Comment