Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.

like image 769
blizpasta Avatar asked Sep 15 '10 07:09

blizpasta


1 Answers

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).

like image 51
Henk Holterman Avatar answered Oct 01 '22 08:10

Henk Holterman