Virtual Methods in Classes

Learn how virtual methods work in classes.

What is a virtual method?

To redefine a method in a derived class, we use a virtual method. Virtual methods are redefined using the virtual keyword in the base class and the override keyword in the derived class.

Syntax

In the parent class:

public virtual void AMethod()
{
  Console.WriteLine("Object of Parent class will run this.");
}

In the child class:

public override void AMethod()
{
  Console.WriteLine("Object of Child class will run this");
}

Example

Get hands-on with 1400+ tech skills courses.