Search code examples
c#inheritancemethod-hiding

C# new not working as expected on derived class-inheritence


Given the following code below. I am wondering why my output is not B A B, but instead B A A

class A
{
    public virtual void display()
    {
        Console.WriteLine("A");
    }
}
class B : A
{
    public new void display()
    {
        Console.WriteLine(" B ");
    }
}
class Program
{
    static void Main(string[] args)
    {
        A obj1 = new B();
        B obj2 = new B();
        obj2.display();
        A r;
        r = obj1;
        r.display();
        r = obj2;
        r.display();
        Console.ReadLine();
    }
}
//Output:
B
A
A

Since r now is a reference to class B(obj2) it should output B, but it is outputting A.


Solution

  • That's not how new works. It is how override works.

    new (Method hiding) only works if your variable type (note that the actual type is irrelevant) is the derived type. Your second test is just polymorphism, and you need override for that.

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

    Side-note, you almost never need method hiding.