How to Override Methods in C#

0
696
How to Override Methods in C#

In object-oriented programming, the term “override” refers to the ability of a derived class to replace or modify the behaviour of a method defined in a base class. When a method is marked with the virtual keyword in the base class, it can be overridden in a derived class by using the override keyword.

Read: How to Overload Methods in C#

To override a method, the derived class must define a method with the same name, return type, and parameters as the method in the base class. The derived class’s method is then marked with the override keyword to indicate that it is intended to override the base class’s method. When the method is called on an instance of the derived class, it will execute the code in the derived class’s method, rather than the code in the base class’s method.

Here is an example of how to override a method in C#:

public class Person
{
   public virtual string ToString()
   {
      return "Person";
   }
}

public class Student : Person
{
   public override string ToString()
   {
      return "Student";
   }
}

In this example, the ToString() method in the Person class is marked with the virtual keyword, which allows it to be overridden in the derived class (Student). The ToString() method in the Student class is then marked with the override keyword, which indicates that it is intended to override the ToString() method in the base class. When the ToString() method is called on an instance of the Student class, it will execute the code in the Student class’s ToString() method, rather than the code in the Person class’s ToString() method.