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:
using System; namespace Polymorphism { class Program { static void Main(string[] args) { MyParentClass MPC = new MyParentClass(); MyChildClass MCC = new MyChildClass(); //Here we will call the method polymorphicly. displayMessage(MPC); displayMessage(MCC); Console.ReadLine(); } private static void displayMessage(MyParentClass MPC) { //Here MyParentClass implementation of MyMethod will be used, even when an instance of MyChildClass is used. //To change that we have to override the parent method in the child class. MPC.MyMethod(); } } class MyParentClass { public int MyFirstProperty { get; set; } public int MySecondProperty { get; set; } /* public void MyMethod() { Console.WriteLine("Message from MyMethod."); } */ //In order to be able to override this method we must make it virtual. public virtual void MyMethod() { Console.WriteLine("Message from MyMethod."); } } class MyChildClass : MyParentClass { /* public void MyMethod() { Console.WriteLine("A little different message from MyMethod."); }*/ //This version of the method will override the original implementation from MyParentClass. public override void MyMethod() { Console.WriteLine("A little different message from MyMethod."); } } }