Tutorialsteacher

Follow Us

Method Hiding in C#

In the previous chapter, you learned about method overriding using the virtual and override keywords. Here you will learn what will happen if we don't use these keywords and still redefine the base class's methods in the derived class?

Look at the following example.

Example: Override Method without Virtual and Override Keywords
class Person
{
    public virtual void Greet()
    {
        Console.WriteLine("Hi! I am a person.");
    }
}

class Employee : Person
{
    public override void Greet()
    {
        Console.WriteLine("Hello! I am an employee.");
    }
}

As you can see, the Greet() method is defined in the base class as well as the derived class without the virtual and override keywords. Now, guess the output of the following program.

Example: Method Hiding
class Program
{
    public static void Main()
    {
        Person p1 = new Person();
        p1.Greet(); 
            
        Person p2 = new Employee();
        P2.Greet();

        Employee emp = new Employee();
        emp.Greet();
    }
}

When you compile the above program, it will give the following warning.

warning CS0108: 'Employee.Greet()' hides inherited member 'Person.Greet()'. 
Use the new keyword if hiding was intended.

However, the above program will successfully run and will give the following output.

Output:
Hi! I am a person. Hello! I am an employee. Hello! I am an employee.

As you can see, the calling of the Greet() method does not depend on the type of object. Here, Employee.Greet() hides the base class method Person.Greet(). This is called method hiding (of base class) in C#.

Method Hiding using new Keyword

Use the new keyword in the derived class to hide the base class method. This will be useful when you are resuing third-party APIs where you don't have control over the base class.

The new keyword will not give the above warning. The following will give the same result but will not give any warning at compile time.

Example: new Keyword
class Person
{
    public void Greet()
    {
        Console.WriteLine("I am a person!");
    }
}

class Employee : Person
{
    public new void Greet()
    {
        Console.WriteLine("I am the Manager!");
    }
}

By using the new keyword with the derived class method, C# treats it as a new method of the derived class and hides the base class method. The Employee.Greet() will be treated as a new method.

The new keyword preserves the relationships that produce that output, but it suppresses the warning. The variables of type base class continue to access the members of the base class, and the variable of type derived class continues to access members in the derived class first, and then consider members inherited from the base class.

Learn when to use override and new keywords.