The Little Known C# ?? Operator

I recently stumbled upon a little known operator in C#, that is pretty slick. It's the "??" operator. Yeah, that's right, it's just 2 question marks. Unfortunately it's nearly impossible to find anything in Google about it, since they don't let you search for characters.

Anyway, this operator is great because it's basically like the SQL IsNull or Coalesce. You can take multiple values, and get the first non-null value.

For example:
object a, b, c, d;

b = null;
c = null;
d = new object();
a = b ?? c ?? d;

Assert.AreEqual(a, d);

I wish I had known about this earlier, it's pretty cool.

For more information, here is the direct MSDN documentation about it.

Also, I'm going to try to list some search terms for anyone looking for information about this. Hopefully Google will index them:
question mark question mark
double question mark
.NET 2.0 coalesce
question mark operator

posted @ Thursday, June 21, 2007 9:50 AM

Print

Comments on this entry:

# re: The Little Known C# ?? Operator

Left by Anonymous at 7/13/2007 2:32 PM
Gravatar
Thanks! I just stumbled upon this syntax as well as was having a hard time finding any information on what it was doing.

# re: The Little Known C# ?? Operator

Left by Anonymous at 7/20/2007 4:34 AM
Gravatar
Actually, this got me thinking about google and searching for weird terms like this. Is it possible with google to use some kind of escape sequence to search for a term like "??"?

# re: The Little Known C# ?? Operator

Left by Grant C at 7/9/2008 10:47 AM
Gravatar
Thanks, that 'double question mark' one got it for me!

# Double Question Mark

Left by Bernard at 7/24/2008 5:06 AM
Gravatar
Thanks, also "stumbled" upon this one via ReSharper suggestion. The "double question mark" helped me to, so I'm using it as 'n Title... will boost the google hits on it :-)

Your comment:



 (will not be displayed)


 
 
 
Please add 5 and 7 and type the answer here:
 

Live Comment Preview: