Friday 10 September 2010

The Null Coalescing Operator (??)

This operator can be extremely useful in situations where you have to check for the value of a variable and if it's null assign an empty string instead (or any other value).

Well you can achieve this using an if statement.

string zVar = somevalue;
if (somevalue == null) {
zVar = string.Empty;


Or you could use the ternary operator (?:)

string zVar = (somevalue != null) ? somevalue : string.Empty;


But we can do better using the null coalescing operator (??)

string zVar = somevalue ?? string.Empty;

No comments:

Post a Comment