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:
class S {} //not sealed, nor does it implement T
interface T {}
class S2 : S, T { }
S s = new S2(); // S reference to an S2 instance, implicit conversion
T t = (T)s; // OK, s refers to an S2 instance that does implement T
Could it be that it is in the specs only to enumerate all syntactically correct ways of expressing an explicit reference conversion, ...
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 unsealed S
, it would have to eliminate the possibility that s
is referencing an S2
type, and that is not practical/possible (S2 could be in another assembly).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With