Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting classes in C#

Tags:

c#

casting

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");
    }
}
like image 589
rgx71 Avatar asked Dec 13 '25 10:12

rgx71


1 Answers

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.

like image 57
Jim D'Angelo Avatar answered Dec 14 '25 22:12

Jim D'Angelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!