C# foreach on IEnumerable<IList<object>> compiles but shouldn't

  • A+

I have the following code:

IEnumerable<IList<MyClass>> myData = //...getMyData  foreach (MyClass o in myData) {     // do something } 

It compiles, runs and obviously I get an System.InvalidCastException.
Why does the compiler not complain? MyClass is a simple bean, no extensions.

Edit 1:
As suggested by David switching the type from IList to List the compiler complains


Well because IList<MyClass> is an interface so theoretically you could have a class that implemented that interface AND derives from MyClass.

If you change it to IEnumerable<List<MyClass>> it will not compile.

In any case, at least I'm getting a warning for suspicious cast, as there is no class in the solution which inherits from both IList<MyClass> and MyClass.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: