You’re never too old to learn it seems… Today, by reading this entry on Ayende’s blog, I discovered the nullcoalescing  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>”)



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;