Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is casting to IList and then calling ToList() when null better than plain ToList()?

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?

like image 699
Mafii Avatar asked Jan 13 '17 12:01

Mafii


People also ask

When should I not use tolist()?

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

How to program against IList instead of list?

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

How to call tolist from an array?

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:

Is it possible to return IList from a model subproduct?

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.


1 Answers

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.

like image 168
YuvShap Avatar answered Oct 05 '22 22:10

YuvShap