Dynamic Polymorphism in C# with Programming Example

In this chapter you will learn:
  • What is Runtime Polymorphism?
  • How to implement it in program?

What is Runtime Polymorphism?

Runtime Polymorphism is also known as Dynamic Polymorphism, Late Binding, Method overriding etc. Whereas in static polymorphism we overload a function; in dynamic polymorphism we override a base class function using virtual or override keyword. Method overriding means having two or more methods with the same name, same signature but with different implementation.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RuntimePolymorphism
{
    class Program
    {
        static void Main(string[] args)
        {
            Chocolate ch = new Chocolate();
            ch.flavor();
            Console.ReadKey();
        }
    }
    class IceCream
    {
        public IceCream()
        {
            Console.WriteLine("Class : Icecream");
        }
        public virtual void flavor()
        {
            Console.WriteLine("IceCream Type : Vanilla");
        }
    }
    class Chocolate : IceCream
    {
        public Chocolate()
        {
            Console.WriteLine("Class : Chocolate");
        }
        public override void flavor()
        {
            Console.WriteLine("IceCream Type : Chocolate");
        }
    }
}

 

Output

Class : Icecream
Class : Chocolate
IceCream Type : Chocolate
_

GuideLine:

  1. If base class function is marked as virtual then it is compulsory to add override keyword in derived class function.
  2. Virtual method allows child class to their own implementation of derived methods.
  3. Virtual method cannot be declared as private.
You can also learn more about virtual method and override keyword here:
https://www.completecsharptutorial.com/basic/c-abstract-and-virtual-method-inheritance-tutorial-with-code/

Summary

In this chapter, you learned Runtime Polymorphism implementation using Virtual and Override keyword. In the next chapter, some programming examples are there that will help you to understand polymorphism clearly.

 

Share your thought