C# | C Sharp Polymorphism

Polymorphism is the combination of two words, poly+forms which means many forms. It is a greek word . In C#, Polymorphism is achieved by mixing three mechanisms that are Inheritance, encapsulation and polymorphism. There are two types of polymorphism named as compile time polymorphism and run time polymorphism. Compile time polymorphism is achieved by method overloading and operator overloading. Runtime polymorphism is achieved by method overriding. Dynamic Method Dispatch: it is used to achieve runtime polymorphism. In this, Call to an    overridden method is resolved at runtime. Let's see an example of runtime polymorphism by dynamic method dispatch. At compile time the compiler checks for the existence of the method in the base class. If the method is derived at runtime then the derived method is called at runtime else the base class method is called. 

using System;
public class Shape
{
            public virtual void draw()
            {
                        Console.WriteLine("drwaing shape...");
            }
}
public class Triangle:Shape
{
            public override void draw()
            {
                        Console.WriteLine("draawing triangle...");
            }
}
public class RuntimePolymorphism
{
            public static void Main(string[] args)
            {
                        Shape s=new Triangle();
                        s.draw();
            }
}
Output
draawing triangle...
C# Polymorphism: with multilevel inheritance
using System;
public class Shape
{
            public virtual void draw()
            {
                        Console.WriteLine("drwaing shape...");
            }
}
public class Triangle:Shape
{
            public override void draw()
            {
                        Console.WriteLine("draawing triangle...");
            }
}
public class RightTriangle:Triangle
{
            public override void draw()
            {
                        Console.WriteLine("drawing RightTriangle");
            }
}
public class RuntimePolymorphism
{
            public static void Main(string[] args)
            {
                        Shape s=new Triangle();
                        s.draw();
                        Triangle t=new RightTriangle();
                        t.draw();
            }
}
Output
draawing triangle...
drawing RightTriangle



ADVERTISEMENT
ADVERTISEMENT