Wednesday 22 February 2012

The null coalescing operator: ??

This is a new feature of c# 2.0. The null coalescing operator is a short cut 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 

string newValue = someValue ?? "default";
 
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".

You could also use this inline:

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

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

No comments :