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

5 Comments so far

  1. Anonymous on July 13th, 2007

    Thanks! I just stumbled upon this syntax as well as was having a hard time finding any information on what it was doing.

  2. Anonymous on July 20th, 2007

    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 “??”?

  3. Grant C on July 9th, 2008

    Thanks, that ‘double question mark’ one got it for me!

  4. Bernard on July 24th, 2008

    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 :-)

  5. Mark on October 5th, 2008

    Thanks… the google search terms did it…

Leave a reply