Given the following:
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();
b = new DC();
b.Display();
}
}
I understand that the following code calls the base class Display() method:
BC b;
b = new BC();
b.Display();
And that the following lines call the derived class Display(), which hides the base class implementation through the use of the new keyword:
b = new DC();
b.Display();
I would like to know what the new keyword is doing internally.
The source of this code included the following explanation:
Since b contains a reference to an object of type DC one would expect the function
Display()of class DC to get executed. But that does not happen. Instead what is executed is theDisplay()of BC class. That’s because the function is invoked based on type of the reference and not to what the reference variable b refers to. Since b is a reference of type BC, the functionDisplay()of class BC will be invoked, no matter whom b refers to.
I am very confused about this particular bit: “because the function is invoked based on type of the reference and not to what the reference variable b refers to”
What does “function is invoked based on type of the reference” mean here
b = new DC();
b.Display();
What is the type of b here? It was declared as instance name of class BC
but later b becomes an instance of class DC.
What you are doing is not overriding, but shadowing. The
newkeyword lets you have aDisplaymethod in both the classesBCandDC, but the methods are not related at all, they just have the same name.To override the method you would need to use the
virtualkeyword for the method in theBCclass, and theoverridesmethod in theDCclass.When you are shadowing a method, it’s the type of the reference that decides which method is used:
Overriding the method looks like this:
When overriding a method, the methods are related, and it’s the actual type of the object that decides which method is used, not the type of the reference:
Another difference between overriding and shadowing, is that when you shadow a method the don’t have to be similar at all, the
newkeyword just tells the compiler that you want to reuse the identifier for something other than in the base class. When overriding a method, the method signatures have to be the same.You can for example shadow a public method that takes a
stringwith something completely different like a private property of the typeint: