Search code examples
c#.netgenerics

How can a generic interface reference accept a non generic object?


I have code

IEnumerable<card> any_object = new card[] { };

where card is a class which doesn't implement IEnumerable. I cannot understand how this code can work ?


Solution

  • From the C# spec:

    In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces.

    So the array does (implicitly) inherit from IEnumerable<card>.

    I don't quite understand the comment about the card class not implementing IEnumerable. The card class doesn't need to, it's the array you're assigning the variable to that has to implement the interface, not the values in it.