I blogged two years ago (See Nullable Value Types and the New ? Syntax, and More on Nullable Value Types) about the new nullable operator in .NET 2.0 (wow, was that really 2 whole years ago? Time flies.). Since then, I waited patiently for it's arrival. Ever since .NET 2.0 came out I've been wanting to return and blog about it again.
Here's a recap on the Null-Coalescing operator. It is a cleaner replacement for ternary conditional operator ?: and has some additional uses as well. Think of the SQL Coalesce function (or IsNull). It is a lot like that. It gives you the first non-null between the two as SQL Coalesce does, but it doesn't allow multiple conditions to be checked as SQL Coalesce does (unless you chain them together). If the left-side is null, it gives you the right side. The right side could be considered your “default“ in case the value on the left is null for some cases. I've always been a fan of using ?: but there was something about needing to, at times, repeat variables in the statement. Here's a sample of what I am talking about:
string name = getName();
Console.WriteLine(name == null ? "No name" : name);
For as much as I love using ?: I've just never liked having to specify the variable name twice in that line. Not a huge deal, but things are even better using the null-coalescing operator in this scenario:
string name = getName();
Console.WriteLine(name ?? "No name");
Much nicer. Gives you the same warm-fuzzy feelings you get from the SQL Coalesce function, doesn't it? It get's even better as you think of the possibilities you have using the new ?? operator. What previously would have been this (with the ?: operator)
Customer customer = Broker.GetCustomer(id);
if (customer == null) customer = new Customer();
Now becomes this:
Customer customer = Broker.GetCustomer(id) ?? new Customer();
I feel the love. But don't forget about nullable types. Nullable types in .NET 2.0 allow you to use a use a value type that can essentially be null. For example, if you have an int, bool, or other value type, it is either uninitialized or a value. Never null. But what if you wanted/needed to indicate null for a value type? A nullable value type is declared with a ? following the type. Let's take a look at a nullable int.
int? id = null;
return id ?? -1;
Ever since .NET 2.0 came out I've wondered why I don't see more of this syntax around. From everything I come accoss I don't find this very often. Maybe people are still getting used to it, but it sure is some cool stuff IMO.