In this article we will learn about the usage of virtual method in C#. Virtual method is a method which can be reusable in the derived class, A virtual method has the implementation in the base class as well as in the derived class.
Sometimes when we define a method inside the base class, so we might have to add some extra functionality to that method, so which can then be achieved using the concept of virtual method by overriding the same method inside the derived class.
A virtual method can be declared with a virtual keyword inside the base class and it can be overridden inside the derived class using the override keyword.
A virtual method is optional to be overridden inside the derived class, If a virtual method is declared inside the base class and it has the same definition inside the derived class, then there is no need of overriding that method, but if a virtual method inside the base class has a definition different to the one inside the derived class, then we must have to override that method inside the derived class.
By default, methods are non virtual and hence they cannot be overridden.
A virtual modifier can only be used with non static modifiers , where as virtual modifier cannot be applied to static, Abstract or private modifiers.
Here, we will consider an example of implementing virtual method in C#, we will create a c# console project in visual studio, we will name it as VirtualMethodExample.
Here we will determine the area for a circle and rectangle by using the mechanism called polymorphism, with the help of which we will override a virtual method with multiple shapes or we can override the same virtual method in more then a single way by deriving the base class from two different classes for the determining the area for a circle and rectangle respectively.
So, as shown above, we have a Shape class having a virtual method called Area, we use inheritance with polymorphism to override this method in more then one way as shown below.
so, as you can see both classes are overriding the same virtual method with different definitions to determine the Areas respectively, here is how the main method looks like.
And, this is what the output looks like on the console window.
Tags
c# programing