Possible multiple enumeration of IEnumerable warning by using .GetType()

597 Views Asked by At

I get the ReSharper warning "Possible multiple enumeration of IEnumerable" with following code:

public void Mymethod(IEnumerable<int> entities)
{
   var enumerator = entities.GetEnumerator();
   var entityType = entities.GetType();
}

As in much stackoverflow-topics described (and also on http://confluence.jetbrains.net/display/ReSharper/Possible+multiple+enumeration+of+IEnumerable) ReSharper recognizes that the query runs twice.

My question is, why the "GetType()" statement is recognized as a query.

Any suggestion?

thanks in advance.

2

There are 2 best solutions below

2
On

In order for GetTypes to be invoked, entities will need to be evaluated from ReSharper's point of view (it doesn't know whether GetTypes will require the enumeration to be evaluated, that's why it says "possible multiple enumeration"). Since ReSharper sees that there are several locations within the method where you have the same scenario, it issues this warning.

This may or may not be a problem, depending on what entities represents and what operation you perform on it. If it represents an in-memory array, or you perform an operation that does not iterate over the list, it's not much to worry about. If you iterate over it, and it represents a query that will go to a database, it's probably good to enumerate it explicitly (by calling ToList or ToArray) and act on the result of that instead.

0
On

It's just Resharper not being smart enough. GetType isn't a virtual method, it can't affect the IEnumerable.