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");
}
}
It is because
Two()is not a virtual method. The only timeTwo()will be called from classBis if you are specifically looking at an instance ofB. ClassAdoesn’t have a lookup table for a virtual method when callingTwo()so nobody knows to look elsewhere for a different method.You can see more details in my answer to this question.