Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play with inheritance [duplicate]

I was just tying to understand what is happening when I write a=c; when I checked type of "a" it is showing up as class "C". Now my question here is if "a" is pointing to "c" then why it is not behaving like pointer "c".

 class Program
    {
        static void Main(string[] args)
        {
            C c = new C();
            A a = new A();
            Console.WriteLine(a.GetType());
            a = c;
            Console.WriteLine(a.GetType());
            a.Show();
            c.Show();
            Console.ReadLine();
        }
    }
class A
{
    public virtual void Show()
    {
        Console.WriteLine("A.Show()");
    }
}

class B : A
{
    public override void Show()
    {
        Console.WriteLine("B.Show()");
    }
}

class C : B
{
    public new void Show()
    {
        Console.WriteLine("C.Show()");
    }
}

Output:

Output

like image 214
Saurabh Saxena Avatar asked Aug 22 '26 07:08

Saurabh Saxena


2 Answers

It's because you're using the new keyword.

The new keyword simply hides the underlying method and replaces it with a new method. When you cast the object to A (or even B), you're using the hidden method in B, not the new method in C.

You can read more about it in the docs here and here.

like image 60
DiplomacyNotWar Avatar answered Aug 23 '26 21:08

DiplomacyNotWar


Actually, it is 'a pointer "c"'. But as @John said, the new keyword is the issue here.

The result would be what you expected for if you didn't set a type to a variable.

For example:

public static void Main()
{
    C c = new C();
    object a = c;
    Console.WriteLine(a.GetType()); // It still is of `C` type instead of object as you've set
    ((A)a).Show(); // Prints out "C.Show" 
    c.Show(); // Prints out "C.Show"
    Console.ReadLine();
}

Once you're expecting an 'A' kind of behavior to the Show method it acts as an A known method. As C have a NEW behavior it's unknown to A (or B), even having an old Show (that's the inherited from B) for ascendents compatibility.

In resume: The Show method of C class is a new one that 'coincidentally' have the same name. But it's known by the C class (and it's children) only.

like image 36
Diego Rafael Souza Avatar answered Aug 23 '26 19:08

Diego Rafael Souza



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!