Search code examples
c#.netcollections

Return zero for Count() on null IEnumerables


I'm getting tired of using code like this:

var count = 0;
if (myEnumerable != null)
{
    count = myEnumerable.Count();
}

And this is a bit pedantic:

var count = (myEnumerable ?? new string[0]).Count();

Is there any tidier way of doing this? I once had a (badly named) PhantomCount extension method on IEnumerable<> that used my first code example, but it had something of a smell about it (besides the name).


Solution

  • 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.