Method hiding (new)
Learn to hide a base method with new and the difference.
Method hiding with new
Sometimes in a derived class you want to hide the base method instead of overriding it. For that you use the new keyword instead of override.
The key difference: hiding with new is a compile-time choice. The method that runs depends on the reference type. If you write Base b = new Derived(); and call b.Greet(), Base.Greet runs because the variable b is typed as Base. Without virtual/override there is no runtime dispatch.
The reference type decides
In the hiding scenario two different calls give two different results. Derived d = new Derived(); d.Greet(); runs Derived.Greet. If you assign the same object to a base reference with Base b = d;, then b.Greet() now runs Base.Greet.
So in hiding it is the reference type, not the object, that decides. This behavior can surprise programmers, so the compiler warns you when you omit the new keyword. To silence the warning you must write new explicitly.
Exercise Show hiding with new
Define a Base class with public void Greet() that prints Console.WriteLine("Base hello"). Define Derived : Base that hides Greet with new and prints Console.WriteLine("Derived hello"). In Main write Base b = new Derived(); and call b.Greet().
Show example solution
Base { public new void Greet() { Console.WriteLine("Derived hello"); } }. In Main add Base b = new Derived(); b.Greet();.
Example solution:
using System;
class Base
{
public void Greet()
{
Console.WriteLine("Base hello");
}
}
class Derived : Base
{
public new void Greet()
{
Console.WriteLine("Derived hello");
}
}
class Program
{
static void Main()
{
Base b = new Derived();
b.Greet();
}
}
Test yourself
-
The hiding keyword
public ____ void Greet() { } // hides the base methodShow answer
public new void Greet() { } // hides the base method -
What does this code print?
Base b = new Derived(); b.Greet(); // Derived.Greet hides with new- Derived.Greet runs
- Base.Greet runs
- Both run
- A runtime error occurs
Show answer
Base.Greet runs — Correct. With new hiding the reference type decides: Base.Greet runs.
-
Match each keyword to its behavior
- new
- Hides a method
- override
- Replaces a virtual method
- virtual
- Enables overriding
- sealed
- Stops overriding