Home » C# Basics » 07 - More C#
7

Method hiding and overriding

Defines what method hiding and overriding is and how it is used in programming

Let us get back to our sample program on inheritance. Remember that when we called the Talk() method using the object of the Student class, the Talk() method of the person class is executed. This is because the Talk() method is inherited by the Student class.

What if we define a Talk() method in the Student class? Modify the Student class as shown:

class Student: Person { private string stream;
public string Stream { get { return stream; } set { stream = value; } }
public void Talk() { Console.WriteLine("Student {0} is talking", this.Name); } }

We have added a Talk() Method in the Student class. Our aim is to execute this method when an object of the Student class calls it. If we run the program, we will get the desired result but we will also get a warning from the IDE:

'ExClassProg.Student.Talk()' hides inherited member 'ExClassProg.Person.Talk()'. Use the new keyword if hiding was intended.

This warning occurs because when we define a method in a derived class which has the same name as that of a method in the base class, the base class method gets hidden (the Talk() method of the Student class hides the Talk() method of the Person class). This is known as method hiding. However, for hiding a base class method, we need to use the new keyword in C#. If we change the above code as:

class Student: Person { private string stream;
public string Stream { get { return stream; } set { stream = value; } }
public new void Talk() { Console.WriteLine("Student {0} is talking", this.Name); } }

Now the warning will not occur because we have used the `new' keyword for implementing method hiding.

In method overriding, the method in the base class is defined with the keyword virtual and the method in the derived class is defined with the keyword override. Hence, in our example, the Person class should be changed as:

public class Person { private string name; private int age; private string gender;
public string Name { get { return name; } set { name = value; } }
public string Gender { get { return gender; } set { gender = value; } } public int Age { get { return age; } set { age = value; } }
public virtual void Talk() { Console.WriteLine("Person {0} is talking", this.Name); } }

The Student class should be as:

class Student: Person { private string stream; public string Stream { get { return stream; } set { stream = value; } } public override void Talk() { Console.WriteLine("Student {0} is talking", this.Name); } }