Wednesday, March 5, 2008

Don't forget about string.IsNullOrEmpty() in .NET 2.0

I have noticed, in my travels though code written by others, that string.IsNullOrEmpty is simply being overlooked.

As most of you know by now, its much better practice, performance wise, to check if length of a string is less than or equal to zero, than comparing it to "" or string.Empty, when trying to determine if its an empty string or not. For those of you who didn't (yes you, in the back, I see you) here is a MSDN article that answers the question. Anyways, I digress and that's not the focus of this post.

The point is that in .NET 1.1 you did the classic:

if( someString == null || someString.Length <= 0 )
return;


Fantastic. However, typing that every time you want to do a "is the string empty check" gets old quite fast. Never fear - MS to the rescue of our ever precious keystrokes. It was decided that in .NET 2.0 that a static function, doing just the above, would become part of the public string interface and save us a little of the hassle.



Now the above code can be "simplified" as:

if( string.IsNullOrEmpty(someString) )
return;


It's a lot more expressive of intent, therefore more readable and as an added bonus, less of a pain to type (a massive 12 chars including white space ;P).



I have just noticed that a great deal of developers either don't now about it, simply don't use it or are still comparing strings to "", hence this post. Not exactly a "wow" or "this-going-to-change-my-life-forever-thank-you-so-much" post, but hopefully it will serve its purpose. It's just a little reminder to those who have made the move from 1.x to 2.0+ (or are just starting) that it's there... aching to be used.

No comments: