Method Overriding in C#

Method Overriding in C# with Examples

In this article, I am going to discuss Method Overriding in C# with examples. Please read our previous article where we discussed Method Overloading in detail. Here in this article, we are going to discuss the following pointers with examples.

  1. What is Method Overriding in C#?
  2. When do we need to override a method in C#?
  3. When a subclass method is treated as an overridden method in C#?
  4. How a method is Overridden in C#?
  5. How to execute the superclass method if it is overridden in the subclass?
  6. What are the differences between Method Overloading and Method Overriding in C#?

Note: The terms Function Overriding and Method Overriding are interchangeably used. Function Overriding is another approach to implement Polymorphism (i.e. Run-Time Polymorphism) in C#.

What is Method Overriding in C#?

The process of re-implementing the superclass non-static and non-private method in the subclass with the same signature is called Function Overriding or Method Overriding in C#. The same signature means the name and the parameters should be the same. The implementation of the subclass overrides (i.e. replaces) the implementation of the superclass method.

The point that you need to keep in mind is that the overriding method is always going to be executed from the current class object. The superclass method is called the overridden method and the sub-class method is called the overriding method.

When do we need to override a method in C#?

If the superclass method logic is not fulfilling the sub-class business requirements, then the subclass needs to override that method with the required business logic. Usually, in most real-time applications, the superclass methods are implemented with generic logic which is common for all the next-level sub-classes.

When is a sub-class method treated as an overriding method in C#?

If a method in sub-class contains the same signature as the superclass non-private non-static method, then the subclass method is treated as the overriding method and the superclass method is treated as the overridden method.

How can we override a parent class method under child class in C#?

If you want to override the parent class method in its child class, first the method in the parent class must be declared as virtual by using the keyword virtual, then only the child classes get the permission for overriding that method. Declaring the method as virtual is marking the method as overridable. If the child class wants to override the parent class virtual method then the child class can do it with the help of the override modifier. But overriding the method under child class is not mandatory for the child classes.

Syntax:
Class1:
Public virtual void show(){} //virtual function (overridable)
Class2: Class1
Public override void show(){} //overriding

Example: Method Overriding in C#

Let us see an example for understanding method overriding in C#. Please have a look at the below code. Here the class “class1” is the parent class and in this class, we defined one method i.e. show() method by using the virtual keyword which marks this method to be overridable in the child class. The class “Class2” is derived from the class “Class1” and hence it becomes a child class of class “Class1” and as soon as it becomes a child class, it got permission to override the overridable method show(). As you can see in the child class we override the show method using the override modifier.

namespace PolymorphismDemo
{
    class Class1
    {
        public virtual void show()
        {
            Console.WriteLine("Super class show method");
        }
    }
    class Class2 : Class1
    {
        public override void show()
        {
            Console.WriteLine("Sub class override show method");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class2 obj = new Class2();
            obj.show();
            Console.ReadKey();
        }
    }
}
Execution Flow:

Now let us understand when we create the object and call the show method as shown below, what happens internally?
Class2 obj = new Class2();
obj.show();
In the above method call, the compiler will search show() method definition in the class “Class2” as the reference type of obj variable is Class2. As it found the method definition in the class “Class2”, so the compilation is successful. At run time, the CLR will check the method implementation in class “Class2” as the reference variable obj holds the Class2 object reference. And it will execute the method from that class. And once you execute the above code, you will get the following output.

Function Overriding in C#

Example: Parent class Reference Variable holding subclass object reference.

The following is the same example as the previous one. But here, the only change is the parent class reference variable holds the sub-class object reference.

using System;
namespace PolymorphismDemo
{
    class Class1
    {
        public virtual void show()
        {
            Console.WriteLine("Super class show method");
        }
    }
    class Class2 : Class1
    {
        public override void show()
        {
            Console.WriteLine("Sub class override show method");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class1 obj = new Class2();
            obj.show();
            Console.ReadKey();
        }
    }
}
Execution Flow:

Now let us understand the execution flow of the above example. When we create the object and call the show method as shown below, what happens internally?
Class1 obj = new Class2();
obj.show();
In the above method call, the compiler will search show() method definition in the class “Class1” as the reference type of obj variable is Class1. As it found the method definition in the class “Class1”, so the compilation is successful. At run time, the CLR will check the method implementation in class “Class2” as the reference variable obj holds the Class2 object reference. And it will execute the method from that class. And once you execute the above code, you will get the following output.

Function Overriding in C#

How can we execute the superclass method if it is overridden in the sub-class in C#?

Once we re-implement the parent class methods under the child class, then the object of the child class calls its own method but not its parent class method. But if you want to still consume or call the parent class’s methods from the child class, then it can be done in two different ways.

By creating the parent class object under the child class, we can call the parent class methods from the child class, or by using the base keyword, we can call parent class methods from the child class, but this and base keyword cannot be used under the static block.

Using the base keyword to call the parent class methods in C#:

Let us see an example for a better understanding. As you can see in the below code, from the child class show method we call the parent class show method using base.show() method call.

namespace PolymorphismDemo
{
    class Class1
    {
        public virtual void show()
        {
            Console.WriteLine("Super class show method");
        }
    }
    class Class2 : Class1
    {
        public override void show()
        {
            base.show();
            Console.WriteLine("Sub class override show method");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Class2 obj = new Class2();
            obj.show();
            Console.ReadKey();
        }
    }
}
Output:

Function Overriding in C#

What is the difference between Method Overloading and Method Overriding in C#?
Method Overloading in C#Method Overriding in C#
It is an approach of defining multiple methods with the same name but with a different signature.It is an approach of defining multiple methods with the same name and with the same signature.
Overloading a method can be performed within a class or within the child classes also.Overriding of methods is not possible within the same class it must be performed under the child classes.
To overload a parent class method under the child class, the child class does not require permission from the parent.To override a parent class method under the child class, first, the child class requires explicit permission from its parent.
This is all about defining multiple behaviors to a method.This is all about changing the behavior of a method.
Used to implement static polymorphism.Used to implement dynamic polymorphism.
This is a code refinement technique.This is a code replacement technique.
No separate keywords are used to implement function overloading.Use the virtual keyword for the base class function and override keyword in the derived class function to implement function overriding.

In the next article, I am going to discuss Method Hiding in C# with examples. Here, in this article, I try to explain Method Overriding in C# with examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this Method Overriding in C# with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *