You’re never too old to learn it seems… Today, by reading this entry on Ayende’s blog, I discovered the null-coalescing operator in C# 2.0. I often use code like the following:
string name = (userName == null? “<no name entered>” : userName);
There’s nothing wrong with this code (although in some cases, the null-pattern is a better alternative) but the ternary operator ?: makes the code less readable, and the fact that you have to specify the userName variable twice has always bothered me somewhat. Well, it seems that someone at Microsoft felt the same and decided to do something about it! In C# 2.0 you can now write
string name = userName ?? “<no name>”;
Of course, in SQL that was already possible with the COALESCE function:
set @name = coalesce(userName, “<no name>”)
Cool!
Remark
This operator allows for a very elegant use of the null-pattern:
public User findUser(string name) {
User user;
// insert some highly advanced search algo here
…
// return found user, or if nothing found, the NullUser instance
return user ?? NullUser.Instance;
}
August 11, 2006 at 10:53 am
Actually I think that SQL function allows you to provide variable number of arguments, of it “Returns the first nonnull expression among its arguments”. This is slightly better than the C# ?? operator. To do it in C# you have to create a method accepting variable number of arguments.
August 11, 2006 at 11:10 am
You can use the ?? operator multiple times in a row, as in return a ?? b ?? c ?? d;
August 11, 2006 at 10:15 pm
Wouldn’t this be more “.NET 2.0-ish”:
string[] list = new string[] { null, null, “not null” };
string firstNotNull =
Array.Find(list,
new Predicate(delegate(string item){
return item != null;
}));