4

I have a class constructor that takes a IList<IElement> as an argument.

When creating a new instance of the class I'm able to pass a IElement[] instead of the IList<IElement> how is that posible?

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
eNepper
  • 1,889
  • 2
  • 13
  • 12
  • 2
    Refer to: http://stackoverflow.com/questions/11163297/how-do-arrays-in-c-sharp-partially-implement-ilistt – Adam Houldsworth Mar 13 '14 at 13:56
  • 1
    `"How and why is this possible?"` - You should get a badge for either clickbait or poorly phrased title. – makerofthings7 Mar 13 '14 at 13:59
  • 1
    @RoyiNamir .. But this is not about array covariance. – dcastro Mar 13 '14 at 14:00
  • @royi This behavious comes from the compiler implementing the interfaces on array types for you, for various reasons. – Adam Houldsworth Mar 13 '14 at 14:01
  • @RoyiNamir Even if it was invariant, you would still be able to convert `IElement[]` into `IList`, simply because single-dimensional arrays are given this implementation at runtime. `T[]` implements `IList`. See the post linked by Adam Houldsworth. – dcastro Mar 13 '14 at 14:02
  • @dcastro Jon says in the answer attached to this question : _Well, I believe it's really due to array covariance_ – Royi Namir Mar 13 '14 at 14:04
  • @RoyiNamir You've taken that quote out of context. That line isn't referring to the fact that `T[]` implements `IList`. It's referring to entirely separate, although related, properties of how arrays implement their interfaces, namely that they are covariant, and they need to maintain that covariance through these interfaces. – Servy Mar 13 '14 at 14:07
  • @RoyiNamir He's referring to the fact that `GetInterfaceMap` fails. – dcastro Mar 13 '14 at 14:07
  • I will read it again. – Royi Namir Mar 13 '14 at 14:08

1 Answers1

10

An array with element type T derives from IList<T>.

This is not visible in the meta-data in mscorlib.dll, but the inheritance relationship is created at runtime in the CLR. C# and the CLR are aware of the array type and treat it specially.

usr
  • 168,620
  • 35
  • 240
  • 369