Virtual Method Explained in C#

Introduction 

In this blog, I will explain the Virtual Method in C#.
 
In object-oriented programing, a virtual method is created in the base class. It uses the virtual keyword, then overrides the keyword using Implement in a base class as well as derived class. A subclass overrides a virtual method by applying the override modifiers. A virtual method can’t be private and it can be exposed to other classes through inheritance. It is runtime polymorphism, late binding or dynamic binding. A virtual method can’t be static or private. It is useful to modify methods, properties, indexers, and events. It can’t access private methods in inherited classes and must be protected in the base class to allow any sort of access. It will use inherited classes.

Examples

  1. public class A  
  2. {  
  3. public virtual void Speed(int carSpeed,int bikeSpeed )  
  4. {  
  5. int carspeed = carSpeed;  
  6. int bikespeed = bikeSpeed;  
  7. Console.WriteLine("Car Speed=" + carspeed);  
  8. Console.WriteLine("Bike Speed=" + bikespeed);  
  9. }  
  10. public virtual void SpeedTest()  
  11. {  
  12. Console.WriteLine("Base class ");  
  13. }  
  14. }  
  15. public class B:A  
  16. {  
  17. public override void Speed(int carSpeed, int bikeSpeed)  
  18. {  
  19. base.Speed(carSpeed, bikeSpeed);  
  20. }  
  21. public override void SpeedTest()  
  22. {  
  23. base.SpeedTest();  
  24. }  
  25. }  
  26. public class Test  
  27. {  
  28. static void Main(string[] args)  
  29. {  
  30. B obj = new B();  
  31. obj.Speed(10, 20);  
  32. obj.SpeedTest();  
  33. }  
  34. }  
  35. }