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 '??'.
Is a shortcut to...
However, it is important to note that it does not take care of the empty string case, which is also vital to check for...
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.
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
Post a Comment