Sohan's Blog

Living the Developer's Life

IsNullOrEmpty() - a Handy Extension Method for IEnumerable

Many a time when you are just about to write a foreach loop on your IEnumerable<T> object you need to check whether the object is null or empty in the following manner

if(myEnumerable != null || myEnumerable.Count() > 0)
{
foreach(<type> item in myEnumerable)
{
}
}

However, with the advent of Extension methods, you can write one custom extension method like the following -

public static class IEnumerableExtensions
{
public static bool IsNullOrEmpty<T>(this IEnumerable<T> instance) where T : class
{
return instance == null || instance.Count() == 0;
}
}

So, you may write the following code instead of the code example presented earlier -

if(!myEnumerable.IsNullOrEmpty())
{
foreach(<type> item in myEnumerable)
{
}
}
There is simple trick with the Extension Method. That is, extension methods can be invoked even on the objects whose reference is not set to an instance of an object or objects with a null value.
So, its perfectly valid to write -
List<string> myList = null;
Console.WriteLine(“myList.IsNullOrEmpty = {0}”, myList.IsNullOrEmpty());
because, the IsNullOrEmpty() is an extension method and can be invoked on a null referencing object of its target type.