C#'s "Coalesce" Operator

[via Spinning the Web] In .NET 2.0, C# has a "Coalesce" operator, which is represented by ??. It it returns the first non-null item from a group of two or more objects.

In case that explanation above doesn't make my meaning clear, this code example will. The following C# code:


return object1 ?? object2 ?? object3

can be used instead of this lengthier code:


if (object1 != null)
{
  return object1;
}
else if (object2 != null)
{
  return object2;
}
else if (object3 != null)
{
  return object3;
}
else
{
  return null;
}

This is old hat for Python and Ruby coders. In Python, here's the equivalent code:


return x or y or z

It'll return the first object whose value is not None, or None if all the objects have that value.

In Ruby, the equivalent is:


x || y || z
Comments
Post a comment
Re: C#'s "Coalesce" Operator
by Andrew Molyneux on Tue 03 Oct 2006 02:42 PM EDT
<pedantry>
I don't know about the Python example, but the Ruby example isn't quite accurate. If Ruby's || did exactly the same as C#'s ??, the following expression:

x = false; y = true; x || y

... would have the value false (because false is non-nil), rather than its actual value: true.
In Ruby, nil and false evaluate to "false" in a Boolean context and anything else is "true". The || operator tests for "falseness", not "nilness".
</pedantry>
Re: Re: C#'s "Coalesce" Operator
Argh. When trying it out in irb, I didn't test by setting values to false. My bad.

I'd hardly call the correction pedantic; I'd simply call it correct. I'll post a correction. Thanks for the heads-up!
Re: Re: Re: C#'s "Coalesce" Operator
by Andrew Molyneux on Wed 04 Oct 2006 11:33 AM EDT
The situation's even worse in Python... apparently zero, empty strings, empty lists, empty tuples and empty hashes are all false.
I can see why it might have been designed that way (not least because I don't think Python had a Boolean type until quite recently) but I think I prefer Ruby's approach.
Post comment:
Format Type: 
  Convert newlines
  Receive comment notifications for this article
Subject: 
   
insert bold tagsinsert italic tagsinsert underline tagsinsert strikethough tagsinsert linkinsert blockquote tags
Comment: 
Comment verification:

Please enter the text you see inside the graphic to post your comment:
You are not currently logged in. If you would like your user information to be displayed with your comment, please enter your login information below.
Login information:
Username: 
Password: 
If you would like to post contact information on your comment, please enter your information into the optional fields below:
Contact information:
Name: 
URL:  example: http://yourdomain.com
Email: 
Please note: email will not be displayed on the site, only for the blog owner. If logged in, URL will only be used.