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

A smart way to do null comparison in csharp

Tuesday, September 05, 2006 3:19 AM

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

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”;
Foo.bar = 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?


Feedback

# re: A smart way to do null comparison in csharp

Console.WriteLine(s == null ? s : "null");
should be:
Console.WriteLine(s == null ? "null" : s); 11/5/2008 8:23 PM | Benson

Post a comment