Explanation for C# Language Specification: 6.2.4 Explicit reference conversions

对着背影说爱祢 提交于 2020-01-15 04:20:28

问题


As I mentioned in this post, I faced a for me not understandable compiler behaviour.

The code:

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

It compiles, but fails on runtime: InvalidCastException; for me it is obvious.

If I change the IList to List as following, it complains:

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

When instead of the class type I put var as following, intellisense recognizes the correct type:

IEnumerable<List<MyClass>> myData = //...getMyData
foreach (var o in myData){}

My first question was: Why doesn't the compiler complain? The answer was that the behaviour respects the C# Language definition. See chapter 6.2.4 Explicit reference conversions, page 116.

Read the 4th and 5th statement:

• From any interface-type S to any class-type T, provided T is not sealed or provided T implements S.

• From any interface-type S to any interface-type T, provided S is not derived from T.

For the second part of the first statement provided T implements S is clear, no doubts.
But why might we cast an interface-type S to any class-type T if it is not derived or not implemented?
In which case/scenario with an non empty list would the code run without throwing an InvalidCastException?

来源:https://stackoverflow.com/questions/53591187/explanation-for-c-sharp-language-specification-6-2-4-explicit-reference-convers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!