C# Polymorphism

C# Code Snippets Polymorphism
Share:

About

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.

Code:

Resulting output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger