Ok I have looked all around and can't find an answer. I have a method that returns an
IEnumerable<ICar>
and the calling method is storing the results of the method in
List<ICar>
but I get the following error.
System.Collections.Generic.IEnumerable<Test.Interfaces.ICar> to
System.Collections.Generic.List<Test.Interfaces.ICar>. An explicit conversion exists
(are you missing a cast?)
I looked on msdn at
IEnumerable<T> interface and List<T> class.
The following line is from msdn.
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection,
IEnumerable
I just don't understand why I can't assign
IEnumerable<ICar> to List<ICar>.
Can someone please explain this to me. What am I missing.
Not all IEnumerable<T>
are List<T>
. The reverse is true.
You can either try to cast to List<T>
which is bad practice and could fail if it really is not a list or you can create a new list from the enumeration
new List<T>(yourEnumerable);
or using Linq
yourEnumerable.ToList();
List<ICar>
implements IEnumerable<ICar>
- you're correct. But that means that you can implicitly convert a List<ICar>
to an IEnumerable<ICar>
- not the other way around. To get around your problem, just call ToList()
on the IEnumerable
to convert it to a List
.
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