I have this code snippet and I would like to know why is the output as written in comment below:
interface I {
void m1();
void m2();
void m3();
}
class A : I {
public void m1() { Console.WriteLine("A.m1()"); }
public virtual void m2() { Console.WriteLine("A.m2()"); }
public virtual void m3() { Console.WriteLine("A.m3()"); }
}
class C : A, I {
public new void m1() { Console.WriteLine("C.m1()"); }
public override void m2() { Console.WriteLine("C.m2()"); }
public new void m3() { Console.WriteLine("C.m3()"); }
}
------
C c = new C();
((I) ((A) c)).m1(); //"C.m1()"
((I) ((A) c)).m2(); //"C.m2()"
((I) ((A) c)).m3(); //"C.m3()"
One original guess of what the output shoud be was:
A.m1();
C.m2();
A.m3();
All these type-casts are redundant and I’m pretty sure they get optimized away by the compiler.
Here’s what I mean.
(A) cis redundant sinceCisA, so we’re left just with(I)c, which is redundant as well, sinceCimplementsI. Thus, we have just an instance ofCclass, for which the compiler applies normal resolution rules.EDIT
Turns out, I was completely wrong. This document describes what happens: