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.List1[MyInterface]'1[MyClass]’.
to type
'System.Collections.Generic.IEnumerable
exception. What am I doing wrong?
A
List<MyInterface>cannot be converted to aList<MyClass>in general, because the first list might contain objects that implementMyInterfacebut which aren’t actually objects of typeMyClass.However, since in your case you know how you constructed the list and can be sure that it contains only
MyClassobjects, you can do this using Linq: