Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of IEnumerable<T> to IList

If a method takes a parameter of type System.Collections.IList can I legitimately/safely pass a value of type System.Collections.Generic.IEnumerable<T>?

I would appreciate a thorough explanation of why this is possible and what actually happens to the object T when the IEnumerable<T> is used inside of the method.

Is it converted to the base type of Object?

Is it used as an System.Collections.IEnumerable?

Are there any scenarios where this will cause problems (i.e. performance issues)?

Thanks in advance, John

like image 797
John Maloney Avatar asked Jan 04 '10 16:01

John Maloney


People also ask

How do I convert IEnumerable to IList?

Convert the IEnumerable<T> instance to a new object which is convertible to IList . For example, in 3.5+ you can call the . ToList() extension method to create a new List<T> over the enumeration.

How to convert List type to IEnumerable in C#?

We can use the AsEnumerable() function of LINQ to convert a list to an IEnumerable in C#.

Should I use IList or IEnumerable?

You should use IList when you need access by index to your collection, add and delete elements, etc., and IEnumerable when you need just enumerate over your collection.


2 Answers

No, You cannot pass an IEnumerable<T> to a method which takes IList. The interface IEnumerable<T> is not convertible to IList and attempting to pass a variable of type IEnumerable<T> to a method taking IList will result in a compilation error.

In order to make this work you will need to do one of the following

  1. Instead of having an IEnumerable<T>, maintain a reference to a type which implements both IEnumerable<T> and IList. List<T> is a good candidate here
  2. Convert the IEnumerable<T> instance to a new object which is convertible to IList. For example, in 3.5+ you can call the .ToList() extension method to create a new List<T> over the enumeration.
like image 157
JaredPar Avatar answered Sep 21 '22 05:09

JaredPar


You will have to call ToList(). http://msdn.microsoft.com/en-us/library/bb342261.aspx

like image 21
Daniel A. White Avatar answered Sep 21 '22 05:09

Daniel A. White