Null Coalescing Operator

I learned something new about C# 2.0 today while using ReSharper: the null coalescing operator which is represented by the ?? keyword.  According to the C# ECMA standard (p.63-64),

The result of a ?? b is a if a is non-null; otherwise the result is b.  Intuitively, b supplies the value to use when a is null.  When a is of a nullable type and b is of a non-nullable type, a ?? b returns a non-nullable value, provided the appropriate implicit conversions exist between the operand types.

In practice, the null coalescing operator can be achieved through the following refactoring (a simple ALT+ENTER which ReSharper will do this automatically for you.  It’ll ask you whether you want to “Replace ‘?:’-operator with ‘??’”).

object Foo()
{
  object someObject = getObject();
  return someObject == null ? “Object is null” : someObject; // <--- This statement will be refactored to use the null coalescing operator

  // Prefer the ternary operator over using conditionals for easy readability.
  // In other words, avoid writing the following statements:

  // if (someObject == null)
  //   return “Object is null”;
  // else return someObject;
}

This is how we can refactor the above method to use the null coalescing operator:

object Foo()
{
  object someObject = getObject();
  return someObject ?? “Object is null”; // <--- This is it.
}

In other words, if the left-side operand is null, the value of the right-side operand will be returned; otherwise the value of the left-side operand will be returned.

This post has been viewed: 1363 times. kick it on DotNetKicks.com

 

Similar posts you might be interested in reading:

One Comment

  1. software development company:

    Nice post,

    I never used ?? I guess it is new to me too

    Anyway, thanks for the post

Leave a comment

Powered by WP Hashcash