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;

6 comments:

Anonymous said...

This sound a lot like Perl (6?)'s logical error operator aka the 'defaulting' operator, //.

Anonymous said...

Or like Ruby's || operator.

return object1 ?? object2 ?? object3;

in Ruby =>

object1 || object2 || object3

Doug said...

Yeah, boo also supports this using the standard logical or operator:

return object1 || object2 || object3

returns the first non-null object, or null if they are all null.

Anonymous said...

And like Pythons OR operator

return object1 or object2 or object 3

Anonymous said...

Of all the other languages, I like the Lisp style of coalesce a lot.

But heres a difference between all the other languages and C#, they are ALL dynamically typed, whereas C# like Java is static typed.

Wonder what happens in the following C# code :-

Dog a_dog = try_dog_init();
Cat a_cat = try_cat_init();
Rat a_rat = try_rat_init();

return a_dog || a_cat || a_rat;

What is the return type, a base class object "Mammal"?

Alex C said...

I think that it would depend on what the return type of the method was supposed to be.

I'm almost thinking that would throw a compile error, even if it was set to return a mammal base class...