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();
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.
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:
DerivedClassC
didn't declare a showMessage
method at all, it would inherit the implementation from DerivedClassB
, right?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.
See more on this question at Stackoverflow