Return zero for Count() on null IEnumerables

Viewed 18407

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

9 Answers

In 2019 the tidiest way to do this is var count = myEnumerable?.Count() ?? 0;.

2021 edit:

public int CountNullable<T>(this IEnumerable<T>? enumerable) =>
    enumerable?.Count() ?? 0;
Related