Empty string or not!

One of the most used methods of the .Net framework I think is String.IsNullOrEmpty(), often used like:

if (String.IsNullOrEmpty(value))

or:

if (!String.IsNullOrEmpty(value))

A few years ago someone notified me that the ‘!’ operator is not very noticeable and therefore its more clear to read it like this:

if (String.IsNullOrEmpty(value) == false)

Code should be self-documenting and readable as a story, because there is a good chance that other developers have to maintain it later! These days a .Net developer is blessed with extension methods. One of the great benefits of extension methods is that they can be applied to null-references without crashing your application! So with the string extensions below you can write the previous statements like:

if (value.IsNullOrEmpty())

or:

if (value.IsNotNullOrEmpty())
public static class StringExtensions
{
  public static bool IsNullOrEmpty(this string value)
  {
    return String.IsNullOrEmpty(value);
  }

  public static bool IsNotNullOrEmpty(this string value)
  {
    return String.IsNullOrEmpty(value) == false;
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: