Method overriding is where a method is invoked from the base class in a derived class. The method in the derived class shares the same name, parameter(s), and return type as the method in the base class. The method in the base class which has been overriden has to have the keywords override, abstract, or virtual.
using System;
public class BaseClass
{
public virtual void DisplayMessage()
{
Console.WriteLine("Base Class") ;
}
}
public class DerivedClass: BaseClass
{
public override void DisplayMessage()
{
Console.WriteLine("Derived Class");
}
}
public class MainClass
{
public static void Main()
{
BaseClass bc = new BaseClass();
bc.DisplayMessage(); //Base Class
bc = new DerivedClass(); //Derived Class
bc.DisplayMessage();
}
}
As you can see in the example above, we use the virtual
keyword in the base class in order to enable that method to be overriden in the derived class and override
in the method in the derived class which is doing the overriding. If we were to remove those two keywords, Base Class
would be printed out twice.