August 30, 2008

Collection.IsNullOrEmpty

Ah, string.IsNullOrEmpty. It was love at first sight when I found that simple yet extremely useful method. It's quite often you want check if a string is null or empty. Instead of checking if the string is null and then checking if it is of zero length (or god forbid checking if it equals string.Empty) you can call this this method and it does it for you. Not only does it save you from unnecessary keystrokes, it also increases readability.

string s = null;
if(!string.IsNullOrEmpty(s))
    PerformWork(s);
instead of
string s = null;
if(s != null && s.Length > 0)
    PerformWork(s);

Well, you probably get my point, it's awesome. But I found that I still write if-statements checking for nullity and length of lists, hashsets and other collections. I can't quite figure out why the BCL team didn't include a corresponding method for collections (or perhaps they did? Enlighten me plix!). Don't despair though, uncle Markus is here to help.

using System.Collections;

namespace freakcode.Utils
{
   public static class Collection
   {
       /// <summary>
       /// Checks if the supplied collection is null or empty
       /// </summary>
       /// <param name="il">The collection</param>
       /// <returns>True if the collection is null or empty, false otherwise</returns>
       public static bool IsNullOrEmpty(ICollection ic)
       {
           return (ic == null || ic.Count == 0);
       }

   }
}

It's so simple it's almost embarrassing to post but it sure increases readability and it's a really great method to integrate and enforce in you own repository of utility methods.

var employees = new List<string>() {"Bob", "Alice", "Tom" };
if(Collection.IsNullOrEmpty(employees))
    FireTheirAsses(employees);

You could rename/copy this to List.IsNullOrEmpty if you think that produces cleaner and more readable code.

Licensing information

kick it on DotNetKicks.com