I have a question about the use of the "new" and "virtual" keywords
together. Say I have the following four classes
class A {
virtual public void f() {
System.Console.WriteLine("A.f()");
}
}
class B : A {
override public void f() {
System.Console.WriteLine("B.f()");
}
}
class C : B {
new virtual public void f() {
System.Console.WriteLine("C.f()");
}
}
class D : C {
override public void f() {
System.Console.WriteLine("D.f()");
}
}
and I use them like this:
class Test {
[STAThread]
static void Main(string[] args) {
C cRef = new D();
cRef.f(); //prints out "D.f()"
A aRef = new D();
aRef.f(); //prints out "B.f()"?!
}
}
It makes sense to me that cRef.f() prints out "D.f()", that is basic
polymorphism. What doesn't make that much sense to me is why aRef.f()
prints out "B.f()". Why should a reference of type A pointing to an
object of type D call B.f()? I realize that it has to do with the fact
that f() is declared as new virtual in C. What I don't understand is
why this is the correct behavior. Why would you even want to do
something like this? How could this be used?
Thanks,
Dave