Lowry Media
Extension Methods - IEnumerable<T> IsNullOrEmpty
May 18, 2008 7:49 PM
Going forward, I will continue to post about useful extension methods that I reuse frequently. Today, I will be talking about IsNullOrEmpty and how we can use this extension method to write less code when dealing with lists.

Frequently, my service methods return lists of things (IList<T>). When these lists are returned, I check to ensure that they are not null and that they have at least one item (count > 0). After seeing this snippet duplicated throughout my code, I decided to pull it into an extension method to reduce the repetition (see DRY). Here is the extension method:

public static bool IsNullOrEmpty<T>(this IEnumerable<T> list)
{
    return list == null || list.Count() == 0;
}

Lists are derived from IEnumerable<T>, so if we leverage IEnumerable as the extension method's base class, then we can reuse it for all types of lists derived from IEnumerable. Here it is in use:

public void SendEmailsToRecipients(IList<string> recipients)
{
    if (recipients.IsNullOrEmpty())
    {
        return;
    }
    foreach (string recipient in recipients)
    {
        DoSomeStuff(recipient);
    }
}

It may not seem like a huge time saver, but it definitely helps explain the intentions of the code clearly. While Lists shouldn't be passed through a method call as null, it still makes sense to test this condition to prevent throwing a NullReferenceException error.
Return to Previous Page
Comments
Comment posted on May 19, 2008 9:21 AM
Ian Davis
Okay, so what's the deal with Ixyz ? IList, IEnumerable. Is this just inheriting from a base, template class?
Ian Davis
Comment posted on May 19, 2008 5:57 PM
Brian
The Ixyz is an interface. It is similar to a base class, except that an interface carries no method bodies (just signatures). When you choose to use an interface, you are forced to implement all of the methods it contains.

The advantage to using an interface is that because all derived classes must implement the methods, you can use polymorphism to do interface-driven coding. Instead of calling the class' methods, you can call the interface methods and it will call the corresponding method on whatever class was instantiated for the interface.

I might blog about this, because it is a core concept in doing dependency injection.
Brian
Add Comment