Combining Method hiding and method overriding in C#

I just could not find a satisfactory explanation for this. So I thought it would help to post this at SO.

What happens when we combine method hiding and overriding in C# ?

For the below example :

class BaseClassA
{
    public virtual void showMessage()
    {
        Console.WriteLine("In BaseClass A ");
    }
}
class DerivedClassB : BaseClassA
{
    public override void showMessage()
    {
        Console.WriteLine("In DerivedClass B ");
    }
}

class DerivedClassC : DerivedClassB
{
    public new void showMessage()
    {
        Console.WriteLine("In DerivedClass C");
    }
}

class Program
{
    static void Main(string[] args)
    {
        BaseClassA a = new BaseClassA();
        a.showMessage();
        a = new DerivedClassB();
        a.showMessage();
        BaseClassA b = new DerivedClassC();
        b.showMessage();
        Console.ReadKey();   
    }
}

I am understanding the output of

 BaseClassA b = new DerivedClassC();
 b.showMessage();

enter image description here

Here's what I understand for new and override in C#

New - It hides the baseclass method. So even if baseclass reference variable points to a derived class object if that derived class hides the method, the output will be baseclass output only.

Override - It overrides the baseclass method. So even if baseclass reference variable points to a derived class object if that derived class overrides the method, the output will be derived class output.

But here how can even a BaseClassA reference variable point to a DerivedClassC object and print DerivedClassB's output ?

Please explain in simple words.

Jon Skeet
people
quotationmark

But here how can even a BaseClassA reference variable point to DerivedClassC object and it prints DerivedClassB's output ?

The code calls the method which is declared by BaseClassA but overridden by DerivedClassB. The method declared in DerivedClassC is a new method, entirely separate from the one declared in BaseClassA... as if it had a different name, in a way.

Effectively, think of it this way:

  • If DerivedClassC didn't declare a showMessage method at all, it would inherit the implementation from DerivedClassB, right?
  • Introducing a new method doesn't change the output because it's a separate method which isn't involved in overriding the method introduced in DerivedClassA. So the output is the same as with the previous step.

I think that trying DerivedClassC as just

class DerivedClassC : DerivedClassB
{
}

and understanding that output is the key to understanding the later behaviour.

people

See more on this question at Stackoverflow