I have an interface defined as:
public interface MyInterface { object foo { get; set; }; }
and a class that implements that interface:
public class MyClass : MyInterface { object foo { get; set; } }
I then create a function that returns a ICollection like so:
public ICollection<MyClass> Classes() { List<MyClass> value; List<MyInterface> list = new List<MyInterface>( new MyInterface[] { new MyClass { ID = 1 }, new MyClass { ID = 1 }, new MyClass { ID = 1 } }); value = new List<MyClass>((IEnumerable<MyClass>) list); return value; }
It would compile but would throw a
Unable to cast object of type 'System.Collections.Generic.List
1[MyInterface]' to type 'System.Collections.Generic.IEnumerable
1[MyClass]'.
exception. What am I doing wrong?
Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List.
The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.
A List<MyInterface>
cannot be converted to a List<MyClass>
in general, because the first list might contain objects that implement MyInterface
but which aren't actually objects of type MyClass
.
However, since in your case you know how you constructed the list and can be sure that it contains only MyClass
objects, you can do this using Linq:
return list.ConvertAll(o => (MyClass)o);
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