Method Overriding in C#

What is Method Overriding?

The implementation of a method in the derived class overrides or replaces the implementation of the method in its base class. This feature is also known as runtime polymorphism because the compiler binds a method to an object during the execution of a program instead of during, the compilation of the program.


Note:
  • Declare the base class method as virtual
  • Implement the derived class method using the override keyword

Example of Function overriding

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Function_Overriding
{
    class A
    {
        public virtual void ShowData()  //declare virtual keyword
        {
            Console.WriteLine("This is A class");
        }
    }
    class B : A
    {
        public override void ShowData()  //declare override keyword
        {
            Console.WriteLine("This is B class");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A a1 = new B();
            a1.ShowData();
            Console.ReadLine();
        }
    }
}

In the preceding code snippet, you can see that in the A class, the ShowData() method is marked with the virtual keyword and in the B class, the ShowData() method is marked with the override keyword.

Output of Function Overriding

This is B class


Write a comment


Name Email Message