Generic Interface Assignment

Hi,
Lets say I have some types defined like this:

public interface IFoo {}
public class Foo : IFoo {}

I then try to compile the following code I get an error:

IEnumerable<IFoo> = new List<Foo>();

Its seems like this isn't allowed by the compiler, but maybe someone could explain why or give me a workaround

thanks,
Jake



Answer this question

Generic Interface Assignment

  • who_am_I

    List<Foo> implements IEnumerable<Foo> but doesn't try to implement enumerators for every interface and base class of Foo. This code has the same problem:
    public class BaseFoo {};
    public class DerivedFoo : BaseFoo {};
    ...
    List<DerivedFoo> lst2 = new List<DerivedFoo>();
    IEnumerable<BaseFoo> enumerable2 = lst2;

    This code compiles:

    List<Foo> lst = new List<Foo>();
    IEnumerable<Foo> enumerable = lst;
    IEnumerator<Foo> enumerator = enumerable.GetEnumerator();
    IFoo obj = enumerator.Current;



  • Generic Interface Assignment