7
votes

When I have a IEnumerable<SomeClass> from which I don't know wheter its a list or not (in terms of List<T>), and I have to enumerate that IEnumerable to make sure that I dont enumerate that enumerable twice (such as looping over it twice, or something like that).

Resharper warns me about possible multiple enumeration of IEnumerable - which is good, sometimes you forget it - and allows you to chose quickfixes:

  • Enumerate to array
  • Enumerate to list

When I chose Enumerate to list, resharper introduces a local variable, and assigns the IEnumerable the following way (example):

  var enumeratedItems = items as IList<SomeClass> ?? items.ToList();

Now my question is:

Why doesn't it simply do items.ToList();?

What's the advantage of trying to cast to IList<SomeClass> first?

1

1 Answers

8
votes

Maybe the IEnumerable is already a list, in this case calling ToList() will just create a new List from an exsiting one, so before doing it resharper suggest to try to cast it first to check if it is an IList or not and only in case it doesn't we will perform the ToList() operation that has some cost.