September 23, 2006

The C# Coalesce Operator

This week I was excited to learn about the coalesce operator, a feature new to C# in .NET 2.0. Coded as a double question mark (??), it works by yielding the first non-null item from a group of two or more objects (as you might expect, this behavior is very much like the COALESCE function in MS SQL). Using this operator can help produce more elegant code if, for example, you've got something like this:
if (object1 != null)
{
return object1;
}
else if (object2 != null)
{
return object2;
}
else if (object3 != null)
{
return object3;
}
else
{
return null;
}

With the coalesce operator the above code block can be refactored into the following:
return object1 ?? object2 ?? object3;