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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With