What does “From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T.” actually mean?
I came across this in the C# Language Specifications here:
6.2.4 Explicit reference conversions
The explicit reference conversions
are:
- …
- From any class-type S to any interface-type T, provided S is not
sealed and provided S does not
implement T.
I can understand what “provided S is not sealed” means, but I’m not sure if I understand what “provided S does not implement T” really mean.
For example:
class S {}//not sealed, nor does it implement T
interface T {}
...
T t = (T)new S();//will throw InvalidCastException.
Could it be that it is in the specs only to enumerate all syntactically correct ways of expressing an explicit reference conversion, regardless of whether it will throw an exception or not? Or does it mean some other thing which I do not know (as of now)?
Thanks in advance.
The pun is in the “not sealed” part:
Yes, the compiler must allow it unless it knows the conversion to be impossible.
If you look at
T t = (T)s;, if S was sealed then the compiler could know with certainty that the conversion was impossible. But with an unsealedS, it would have to eliminate the possibility thatsis referencing anS2type, and that is not practical/possible (S2 could be in another assembly).