Sunday 20 July 2014

Null-coalescing operator in C#

It feels like I’ve been using C# forever. When you’ve been doing something for a long time it’s easy to fall into habits and miss or forget about techniques that could make your life a little easier so it doesn’t hurt to remind ourselves of things from time to time.

I have used many DI containers like Spring.Net, Unity, NInject etc. but I recently started using StructureMap for the first time. I added it to an MVC project using NuGet and when I looked at the code that had been added to my project I saw code like this:

protected override IEnumerable<object> DoGetAllInstances(Type serviceType) 
{
	return (this.CurrentNestedContainer ?? this.Container).GetAllInstances(serviceType).Cast<object>();
}

It really struck me that I couldn’t remember the last time I used the null-coalescing operator (??). Some quick revision:

“The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.” [1]

The C# Reference goes on to describe more features of the ?? operator:

  • You can use the ?? operator’s syntactic expressiveness to return an appropriate value when the left operand has a nullable type whose value is null.
  • If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error.
  • If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.
  • The result of a ?? operator is not considered to be a constant even if both its arguments are constants.

So, by way of example, the following statements are all equivalent:

return nullableValue ?? someOtherValue;

return nullableValue != null ? nullableValue : someOtherValue;

if(nullableValue != null)
{
    return nullableValue;
}
else
{
    return someOtherValue;
}

References

Sunday 20 July 2014