Saturday, July 16, 2011

C# 2.0 - Null Coalesce Operator

Null coalesce operator (??) was a very nice feature of C# 2.0. Null coalesce converts nullable type to non-nullable type. The ?? operator uses to define a default value for nullable type. For that in previous version of C#, we have to right like as bellow.

long lngMarks;
long lngAvg = (lngMarks == null ? 0 : lngMarks) / 6;

In above case, we use ternary operator(?) for check, value is null or not. Now it is more easy with Null Coalesce operator (??). We can use the Null - Coalesce Operator (??) as a shortcut for that expression, as shown here:

long lngMarks ;
long lngAvg = (lngMarks??0) /6;


Null coalesce operator(??) is a very small but very useful feature of C# 2.0.

No comments:

Post a Comment