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.