In this code snippet, we will take a look at polymorphism, the virtual and the override keywords in C#.
Polymorphism is one of the main concepts of OOP(object-oriented programming). It means that child classes can be viewed as parent classes at run time.
Suppose we have a method that takes a parent class as an input. We can pass it the derived class and everything will still work. This can work because the child method inherits the required members from the parent class.
However, we now run into a problem. What if we want to implement our own version of the method and not use the parents’ version?
Well, this is why we have the virtual and override keywords.
Virtual: The virtual keyword enables the method to be overridden in the derived(child) class. In other words, if a method isn’t marked as virtual in the parent class no child class will be able to override it.
Override: The override keyword will make the current method of the child class override the original implementation of the parent class.
Let’s have a look at the code below to see how polymorphism looks like and how the virtual and override keywords are used.