Casts that makes no sense (!)
Ary Borenszweig
ary at esperanto.org.ar
Mon Mar 8 06:38:08 PST 2010
The following compiles:
import std.stdio;
interface I {
}
class A : I {
}
class B {
}
int main() {
I i = new A();
A a = cast(A) i;
B b = cast(B) i; // shouldn't compile
B c = cast(B) a; // shouldn't compile
writeln(a);
writeln(b);
writeln(c);
return 0;
}
But two lines there doesn't make sense:
B b = cast(B) i;
An instance of I can never be a B, so why the cast is allowed?
B c = cast(B) a;
An instance of A can never be an A, so why the cast is allowed?
I think these casts should result in an error. This can prevent some bugs.
Java and C# work like that. You can't cast an object of instance of type
A to type B if both types are classes and B isn't a supertype or subtype
of A.
More information about the Digitalmars-d-learn
mailing list