Wednesday, December 23, 2009

Useful Extension methods

I've posted in the past about the hazards in extension methods and how they can be easily abused. there are plenty of links out there specifying the cons of using this feature.
However, since the title got you in here, I'm assuming you are still interested.
I wanted to share some of the most common extension methods I use when writing code.

IsNullOrEmpty - I think we all know this method from the String class. Why not have the same capability on collections?
I did see plenty of samples on the web showing how to add this method to collections or arrays.
things like:
public static bool IsNullOrEmpty(this ICollection collection)
{
    return collection == null || collection.Count == 0;
}

This is all fine and will return True if the collection/Array are null or empty.
But hey, what about some other, non "ICollection" objects that implements IEnumerable like XmlNodeList?
For that purpose, we can't use the Length or Count properties since we don't have them.
So, let's work with the IEnumerator.
Initially, the enumerator is positioned before the first element in the collection so calling Current will throw an exception. By calling MoveNext we move the enumerator to the first element and the bool value will tell us if it is empty or not. Complicated?
public static bool IsNullOrEmpty(this IEnumerable iEnumerable)
{
    if (iEnumerable != null)
    {
        return !iEnumerable.GetEnumerator().MoveNext();
    }
    return true;
}

Now, since collections and arrays implements IEnumerable we are clear to go.
static void Main(string[] args)
{                        
    List<string> list = new List<string>();
    Console.WriteLine(list.IsNullOrEmpty());//This will print True
    list.Add("Some text");
    Console.WriteLine(list.IsNullOrEmpty());//This will print False
}

But wait, didn't I say "some" extension methods?
Another one I use when I'm writing console applications is:
public static void Print(this Object obj)
{
    Console.WriteLine(obj);
}
I use this trick when I need to change the output target according to configuration or command line input.
The result will look this:
static void Main(string[] args)
{                        
    List<string> list = new List<string>();
    list.IsNullOrEmpty().Print();//This will print True
    list.Add("Some text");
    list.IsNullOrEmpty().Print();//This will print False
}

No comments:

Post a Comment