Explain the use of Virtual Keyword in C# ?
Answer:
When we want to give permission to a derived class to override a method in base class, Virtual keyword is used. For example. lets us look at the classes Car and Ford as shown below.
class Car { public Car() { Console.WriteLine("Base Class Car"); } public virtual void DriveType() { Console.WriteLine("Right Hand Drive"); } } class Ford : Car { public Ford() { Console.WriteLine("Derived Class Ford"); } public void Price() { Console.WriteLine("Ford Price : 100K $"); } public override void DriveType() { Console.WriteLine("Right Hand "); } }
When following lines of code get executed
Car CarFord = new Car(); CarFord.DriveType(); CarFord = new Ford(); CarFord.DriveType();
Output is as given below.
Base Class Car Right Hand Drive Base Class Car Derived Class Ford Right Hand