Take the 2-minute tour ×

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]' to type 'System.Collections.Generic.IEnumerable1[MyClass]'.

exception. What am I doing wrong?

share|improve this question
add comment

2 Answers

up vote 10 down vote accepted

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);
share|improve this answer
This will work in .Net 2.0+ and not just LINQ as System.Collections.Generic.List<> supports ConvertAll<T>() directly. –  Ritch Melton May 16 '11 at 15:44
Thanks, @Ritch. I thought that ConvertAll was a Linq method, but I hadn't bothered to check. –  JSBձոգչ May 16 '11 at 15:47
This did the trick! Thanks JSBangs. –  acermate433s May 16 '11 at 15:49
Actually, if you are sure that your list contains only MyClass objects, you should use Enumerable.Cast<TResult> Method, and you will get an InvalidCastException if an element in the sequence cannot be cast to MyClass. –  Paolo Moretti May 16 '11 at 15:50
@PaoloMoretti: Thanks - your method saved a lot of effort. I am using telerik wpf components and in the RadDataFilter the return value is a list of interfaces and I have to do a long foreach with typecasting and string match switches and if else. Now I can use linq. :) –  akshaymishra14 Jun 6 '13 at 7:07
add comment

But a List<MyInterface> is emphatically not a List<MyClass>.


interface IAnimal { }

class Cat : IAnimal { }
class Dog : IAnimal { }

var list = new List<IAnimal> { new Cat(), new Dog() };


var cats = (List<Cat>)list;



var cats = list.Cast<Cat>();



var cats = list.ConvertAll(x => (Cat)x);


Instead, you could say

var cats = list.OfType<Cat>();
share|improve this answer
I see. I was confused because you can cast an interface to its concrete class. Thanks. –  acermate433s May 16 '11 at 15:55
add comment

Your Answer


