Return zero for Count() on null IEnumerables

I don't think using extension method is a bad idea.

public static int NullableCount<T>(this IEnumerable<T> collection)
{
   return collection == null ? 0 : collection.Count();
}

The problem is really in whatever is creating these enumerables. Unless you have a really good reason, anything that generates an iterable collection should return an empty collection instead of null. This would align with the Null-Object-Pattern, hence the benefits are the same.

My suggestion would be to fix whatever produces myEnumerable, or if you can't do this, add a check way earlier to see if it's null and react appropriately.


I use a custom extension method:

public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
{
    return source ?? Enumerable.Empty<T>();
}

...

int count = myEnumerable.EmptyIfNull().Count();

How about

count = myEnumerable == null? 0 : myEnumerable.Count()