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.
Similar posts you might be interested in reading:
- How to recursively traverse a DOM element in JavaScript
- Quickly Search For An Exact Match in .NET Reflector
- Getting Familiar With Your Basic .NET Delegates
- Inserting and Retrieving An Image In SQL Server 2005
- Rely on your experience and knowledge over some tools’ recommendations
- Avoid calling a virtual or abstract method from a constructor in C#…especially in VB!
- The Case for ReSharper in the Enterprise






software development company:
Nice post,
I never used ?? I guess it is new to me too
Anyway, thanks for the post
August 18, 2009, 8:33 am