What is virtual method in C# language and why do you use it?

(Last Updated On: April 8, 2017)

Answer: A virtual method in C# language is method that have virtual keyword in its declaration. In c# inheritance feature, we may want to allow derived classes to have their own implementation for some of the methods resides into a base class.

For this purpose, we use virtual keyword in method declaration in base class, so, that derive class can override it and implement its own feature.

In below c# code example, we have “Printer” base class that have two method print() and display(). print()method does printing and display() function will have display unit of dimension of 5×5 units.

Here, we want to have a derived class “LaserJet” printer that will use the print() method of base class, but, will have display unit of 10×10.

So, we will declare base class display() method as virtual and override it into derived class and implement new dimension of 10×10.

 

NOTES:

Virtual keyword is different from “abstract” as virtual keyword does not force derived class to implement it, but, abstract forces derived classes to implement it.