Thoughts on a Resharper 6 refactoring

Consider the following code:

var foo = new List() { /* ... */ };

If we want to know if there are no items in the list we have 3 possibilities (probably more, but I’ll limit myself to 3 possibilities in this scope).

bool listEmpty = foo.Count == 0;

Which just uses List’s implementation of ICollection.Count.

Second option is:

bool listEmpty1 = foo.Count() == 0;

Last option is:

bool listEmpty2 = foo.Any();

As you might know, since ReSharper 6, the second option is suggested to be refactored to the last option.


However it is not the same to do an Enumerable.Count() and a Enumerable.Any() on an ICollection.

If we take a closer look using a decompile tool (Reflector, Resharper Decompile, JustDecompile, …) at the Count() and Any() extension methods we see the following:



We can clearly see that when using the Count() extension method the system actually first tries to see if the the IEnumerable<TSource> is an ICollection<TSource> or an ICollection, and using the Count property if possible, before enumerating over the entire list.

So I say: not everything Resharper says is correct, always use it carefully, think before you do an automatic refactoring. And more importantly: think about the design of your code. Is it needed that you pass in an IEnumerable? Is an ICollection<TSource> or an IList<TSource> more useful?

Have a good one!