Aquarium Blog

Wednesday, May 30, 2007

IsNullOrEmpty for IEnumerable

This is not extremely relevant, but String.IsNullOrEmpty() has become a very popular time saver, and I think the same concept should be applicable to arrays and collections.

I found on Microsoft Connect that someone already added a suggestion to add IsNullOrEmpty to arrays on 2005.

This is not a big discovery, but I have been playing with extension methods in Orcas and they are so nice!

What if I define this?

public static class IEnumerableExtensions
{
    public static bool IsNullOrEmpty(this   System.Collections.IEnumerable source)
    {
        if (source == null)
            return true;
        else
            return !source.GetEnumerator().MoveNext();
    }
}

Once you import the appropriate namespaces, all these things are possible:

string a = null;
Console.WriteLine(a.IsNullOrEmpty());

var b = new Dictionary();
Console.WriteLine(b.IsNullOrEmpty());

MemberInfo[] d = MethodInfo.GetCurrentMethod().DeclaringType.GetMembers();
Console.WriteLine(d.IsNullOrEmpty());

var g = from f in d
where f.MemberType == MemberTypes.NestedType
select f;
Console.WriteLine(g.IsNullOrEmpty());

I would like to see something like this included in System.Linq.Enumerable static class. Then it would be available to everyone, by default.

Update: I added a more complete entry as a suggestion on Microsoft Connect.

Update 2: At the Connect site, Mads teaches me why he thinks IsNullOrEmpty as an extension method is really a very bad idea. Basically, using the variable.Method invocation syntax on a method that is meant to work when the variable is null, it is very inconsistent with the instance method invocation semantics one usually gives to this syntax in languages like C# and VB.

I still think that the method, probably defined as a static method, would be nice to have on Enumerable (because it is already a well-known place to find methods that apply to the IEnumerable interface). Also, I think there is some void in the definition of extension methods. Its designers think that calling them on null instances should generally throw an exception, so why do I need to check for the parameter and throw the exception myself?