0
class BC
{
    public virtual void Display()
    {
        System.Console.WriteLine("BC::Display");
    }
}

class DC : BC
{
    public virtual void Display()
    {

        System.Console.WriteLine("DC::Display");

    }
}

class TC : DC
{
    public virtual void Display()
    {
        System.Console.WriteLine("TC::Display");
    }
}



class Program
{
   public static void Main()
   {
       BC b;
       b = new BC();
       b.Display();

       b = new DC();
       b.Display();

       b = new TC();
       b.Display();


   }
}

why output is not "BC::Display DC::Display TC::Display"?

xanatos
  • 109,618
  • 12
  • 197
  • 280
guruD
  • 7
  • 5
  • Check this: https://stackoverflow.com/questions/23313408/why-is-cant-use-overriding-method-in-c-not-about-keyword?rq=1 – Nikola May 20 '15 at 09:31
  • 1
    The compiler warnings give a hint to why this is happening. You are hiding the inherited members. – Dirk May 20 '15 at 09:31

2 Answers2

0

Only the method in the base class needs to be marked virtual. The methods in the derived classes should be marked as override, otherwise they hide the underlying methods. Since they're "different" methods, and b is of type BC, the compiler will route all calls to BC.Display.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
0

If you compile it in Visual Studio, you'll get these warnings:

Warning 2   'Workbench.Program.DC.Display()' hides inherited member 'Workbench.Program.BC.Display()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. C:\Users\Alberti\Documents\Visual Studio 2013\Projects\Workbench\Workbench\Program.cs   328 29  Workbench
Warning 3   'Workbench.Program.TC.Display()' hides inherited member 'Workbench.Program.DC.Display()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. C:\Users\Alberti\Documents\Visual Studio 2013\Projects\Workbench\Workbench\Program.cs   338 29  Workbench

You must use override instead of virtual in DC and TC, otherwise you are doing a new virtual and creating a new method that isn't "overriding" the BC.Display but that is simply "hiding" it.

There is a good explanation here: https://stackoverflow.com/a/6162547/613130 about the difference between virtual/override and new

Community
  • 1
  • 1
xanatos
  • 109,618
  • 12
  • 197
  • 280