Reputation: 857
I have a question, why in this code, One() method is execute from class B and Two() method is executed from class A? I know that is doing casting, but I don't understand the way is working. By the way, any good link or book with this kind of tricks will be much appreciated. Than you.
class Program
{
static void Main(string[] args)
{
B b = new B();
A a = (A)b;
a.One();
a.Two();
}
}
public class A
{
public virtual void One()
{
Console.WriteLine("A One");
}
public void Two()
{
Console.WriteLine("A Two");
}
}
public class B : A
{
public override void One()
{
Console.WriteLine("B One");
}
public new void Two()
{
Console.WriteLine("B Two");
}
}
Upvotes: 3
Views: 163
Reputation: 667
The Two() method is not virtual in class A (so it does not allow it to be overridden, almost for the same reason you had to make B.Two() as new - otherwise the compiler would have complained).
So when you dont have a virtual method in the base class it is not meant to be overridden. Thus when you cast object of type B to type A the call to Two() method is bound to the method table of type A and not type B.
You can read more about it here:
http://msdn.microsoft.com/en-us/library/6fawty39(v=vs.80).aspx http://www.akadia.com/services/dotnet_polymorphism.html
Upvotes: 0
Reputation: 3952
It is because Two()
is not a virtual method. The only time Two()
will be called from class B
is if you are specifically looking at an instance of B
. Class A
doesn't have a lookup table for a virtual method when calling Two()
so nobody knows to look elsewhere for a different method.
You can see more details in my answer to this question.
Upvotes: 5