What is the purpose of virtual keyword in .NET?Virtual keyword
means that the method or property or indexer or declaration of an event
associated with virtual keyword in the base class can be overridden by
the derived class. Here is an example to demonstrate the usage of virtual
keyword to override a method:
class baseEmployee { public float empSalary; public virtual void assignSalary(float amt) { empSalary = amt; } public void displaySalary() { Console.WriteLine(Salary = {0}, empSalary); } class derivedSupervisor
: baseEmployee { class derivedLabor:baseEmployee
{ class testClass
{ In this example, you have defined a virtual method called assignSalary in the base class which is used to assign salary for the employee based on the amount that is passed as argument. This base class is derived by two derived classes namely derivedSupervisor, derivedLabor. These derived classes are allowed to override assignSalary method of baseEmployee because the method is defined as virtual. While overriding, these two derived classes include their own computation method for assigning salary. Note that if the keyword virtual is not mentioned in assignSalary of baseEmployee and you define the same method in the derived classes, then it is not overriding. The method definitions in derived class are considered as new method that is independent of the base class method.
|