This one is a bit controversial because what I’m really saying is that I want to call an extension method on null and have it return true, rather than a Null Reference Exception. This violates the best practice of keeping null semantics on extension methods, but it makes my code so easy to write, so I don’t care, I wish it was there.
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
if(source ==null) return true;
var collection = source as ICollection<T>;
if (null != collection && collection.Count==0) return true;
var enumerator = source.GetEnumerator();
return enumerator.MoveNext();
}
I say that it makes my code writable because I can write what I’m thinking.
if (somedata.IsNullOrEmpty()) takeAction(); else takeOtherAction();
I’m cool with this too. As it turns out the BCL LINQ extension methods actually raise ArgumentNullException instead of NullReferenceException which gives you even more justification here.
-Chris