Geeks With Blogs
Hannes Pavelka It isn't rocket science. Well, unless of course you're NASA

C# 2.0 offers a new null coalescing operator: ?? You can look it up in C# Language Specification (

The ?? Operator “take the first value if it is not null, otherwise the second.”

I consider this a pretty smart way to do some null comparision where you would usually use an if==null construct.

Here is a quick example:

string user = “Hannes”; = user ?? “unkown”;
This will set Foo.Bar to “Hannes”.
int? x = null;
int? y = 2;
int result = x ?? y;
This will set result to 2;

The operator works on nullable value types and on reference types.
I assume if you like the tenary operator you will love the new null coalescing operator.
The following three lines are logically identically:

if (s != null){ConsoleWriteLine(s);}else{ConsoleWriteLine("null");}

Console.WriteLine(s == null ? s : "null");

Console.WriteLine(s ?? "null");


Nice isn't it?

Posted on Tuesday, September 5, 2006 3:19 AM | Back to top

Comments on this post: A smart way to do null comparison in csharp

# re: A smart way to do null comparison in csharp
Requesting Gravatar...
Console.WriteLine(s == null ? s : "null");
should be:
Console.WriteLine(s == null ? "null" : s);
Left by Benson on Nov 05, 2008 8:23 PM

Your comment:
 (will show your gravatar)

Copyright © Hannes Pavelka | Powered by: