Programming tidbit - be careful with the null coalescing operator on strings

One of my favorite shortcuts in programming with C# is the null coalescing operator, better known as '??'.

var something = aString ?? "somethingelse";

Is a shortcut to...

var something = aString == null ? "somethingelse" : aString;

However, it is important to note that it does not take care of the empty string case, which is also vital to check for...

var something = string.IsNullOrEmpty(aString) ? "somethingelse" : aString;

Unless you can absolutely guarantee that a string will either be null or have a value, the '??' operator then becomes useless (sadly) for strings.

EDIT:  As of .NET 3.5, you cannot overload this operator, so I would not recommend using this operator with strings, unless an empty string is acceptable.

Comments

Popular posts from this blog

35x Improved T-SQL LevenShtein Distance Algorithm...at a cost

The hidden workings of __doPostBack - Full or Partial Postback?

Facing Death...dum de dum dum