Thursday, June 30, 2011

C# Shortcuts (?? Null Coalesce Operator)

How often to check for null values ​​in the code?
Then the null-coalesce operator (??) is convenient. To see how this works, consider the following sample code.


object c = null;
object a = new object();
object b;

if (c != null)
    b = c;
else
   b = a;
Now using the "?" conditional statement you may write it as...
object c = null;
object a = new object();
object b = (c != null) ? c : a;
Now make it even shorter using ?? null-coalesce operator...
object c = null;
object a = new object();
object b = c ?? a;

No comments:

Post a Comment