Skip to main content

Method Overriding with C#

Method overriding is a feature that allows you to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance.

Let's understand method overriding using few examples.


Output

Above code consists of base class A and a derived class B. Class A consists of method Show(). Class B hides the function Show() it inherited from the base class A by providing its on implementation of Show().

In the above code we first created object of type A. Using the reference variable “a” we invoke the function Show(). As expected,  Show() of class A is executed because the reference variable “a” refers to the object of class A. Then we created an object of Derived class B and storing its reference in the reference variable “a” of type A. Using the reference variable “a” we invoke the function Show(). Since “a” contains a reference to an object of type B we would expect the function Show() of class B to get executed. But that does not happen. Instead what is executed is the Show() of A class. That's because the function is invoked based on a type of the reference and not to what the reference variable “a” refers to. Since “a” is a reference of type A, the function Show() of class A will be invoked, no matter whom “a” refers to.

We can use keywords virtual and override to overcome this problem as shown in the following example.

Output

The method Show() of Base class A is declared as virtual, while the Derived class's implementation of Show() is declared as override. Doing so enables C# to invoke functions like Show() based on objects the reference variable refers to and not the type of reference that is invoking the function. Hence in the above program when “a” refers to the object of class A it invokes Display() of class A and then when b refers to the object of class B it invokes Show() of class B.

Comments