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:
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?
Generally you should not use ToList () unless work you are doing cannot be done without converting collection to List. For example if you just want to iterate through the collection you don't need to perform ToList
it's best to program against the interface (IList) instead of the implimentation (List). It's an unneeded cast to go to List. You now have to add error handling if on the off chance an implementation of IList, which is not a List, enteres that code path. List<SubProduct> subProducts = new List<SubProduct> (Model.subproduct);
Calling ToList () will simply copy the source array and wrap it in a List<T> object. Even the performance of the second case is not something to worry about for small collections. If you disassemble the source code of the constructor that takes an IEnumerable<T>, you will see it will do a few things:
Model.subproduct returns IList<SubProduct>. it's best to program against the interface (IList) instead of the implimentation (List). It's an unneeded cast to go to List. You now have to add error handling if on the off chance an implementation of IList, which is not a List, enteres that code path.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With