Polymorphism is the idea that you can call a particular method based on the class that was used to create the instance of the object. In C#, you must use the override and virtual keywords explicitly to gain this functionality.
A virtual method is a method in a base class that can be ignored in favor of a derived class’s version of the same method. Caution It is quite easy to confuse the concept of overriding with that of overloading. The big difference between these two concepts is the basis of polymorphism. A virtual method can be overridden by a method of a derived class that has the exact same prototype or method signature. Overloading a method is when the method has the same name but not the same arguments in the same order.
Pure virtual methods are used in abstract classes, and they do not have a method definition. They exist solely as a placeholder for a derived class to implement that inherits from the abstract class.
Other than in abstract class, we can define virtual methods in normal classes by using virtual keyword. Inherit the base class in child class and override the base class virtual method by using override keyword.
The following example demonstrates the use of virtual methods by using normal classes.
Employees.cs
using System;
namespace CSharpVirtualExp
{
class Employees
{
public virtual void Display()
{
Console.WriteLine("This is virtual method");
}
}
}
Employee.cs
using System;
namespace CSharpVirtualExp
{
class Employee : Employees
{
public override void Display()
{
Console.WriteLine("This is method using override keyword");
}
}
}
Program.cs
using System;
namespace CSharpVirtualExp
{
class Program
{
static void Main(string[] args)
{
Employee obj = new Employee();
obj.Display();
Console.ReadLine();
}
}
}
As shown above, Employees class has Display() method using virtual keyword and Employee class inheriting the Employess class and overriding the Display() method by using the override keyword.