In C#, Method Overriding is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions. from another class (base class) in the derived class.
Creating a method in the derived class with the same signature as a method in the base class is called method overriding. It is used to achieve runtime polymorphism.
To perform method overriding in C#, you need to use virtual keyword with the base class method and override keyword with the derived class method.
C# Method Overriding Example
We are going to a simple example of method overriding in C#. In this example, we are overriding the eat() method by the help of the override keyword.
using System;
public class DOG{
public virtual void eat(){
Console.WriteLine("Eating...");
}
}
public class COW: DOG
{
public override void eat()
{
Console.WriteLine("Eating bread...");
}
}
public class OverridingExample
{
public static void Main()
{
COW c = new COW();
c.eat();
}
}
Output
Eating bread...