Use “??” for avoiding null

There is a nifty operator in dotnet2, ??

Use it to get the first thing that is not null.
   string name = firstName ?? lastName ?? email ?? “Has no name”;
sets name to the first value that is not null.

To set  a string to empty if it is null but keep it otherwise:
    message = message ?? string.Empty;
which is  the same as
    if( null ==  message ){
message = string.Empty;
}

One might consider it harder to read but I think it is a matter of getting used to.

Beware though of its low precedence.
    string user = userName ?? string.Empty +  description;
will always return only the userName if there is one.   Alas, insert a pair of parenthesises:
string user = ( userName ?? string.Empty ) +  description;

On the side I prefer
   string.Empty
to
   “”
because with string.Empty I am totally sure the string is empty.  There is no chance what so ever that a stray space slipped in between the quotes.

Tags:

Leave a Reply