find and solve || findandsolve.com
Please wait.....

Understanding Polymorphism In C#

In the C# OOPS, Polymorphism is a Greek word, which means "one name many forms". In other words, one object has many forms or has one name with multiple functionalities. "Poly" means many and "morph" means forms. Polymorphism provides the ability to a class to have multiple implementations with the same name

There are two types of polymorphism in C# programming language: The first one is compile-time polymorphism and the other is runtime polymorphism. Compile-time polymorphism is achieved by method overloading and operator overloading in C#. Polymorphism is also known as static binding or early binding. Runtime polymorphism is achieved by method overriding which is also known as dynamic binding or late binding.


C# Runtime Polymorphism 

using System;  

public class Animal{
    public virtual void eat(){
        Console.WriteLine("eating...");
    }
}
public class Cat: Animal
{
    public override void eat()
    {
        Console.WriteLine("eating bread...");
    }
}
public class PolymorphismExample
{
    public static void Main()
    {
        Animal cat= new Cat();
        cat.eat();
    }
}  

Output

eating bread...


Other C# Runtime Polymorphism

using System;  

public class Example{
    public virtual void Test(){
        Console.WriteLine("Test...");
    }
}
public class Test1: Example
{
    public override void Test()
    {
        Console.WriteLine("Test1...");
    }
}
public class Test2 : Example
{
    public override void Test()
    {
        Console.WriteLine("Test...");
    }
}
public class PolymorphismExample
{
    public static void Main()
    {
        Example example;
        example = new Example();
        example.Test();
        example = new Test1();
        example.Test();
        example = new Test2();
        example.Test();
    }
}  

Output

Test...

Test1...

Test...


Runtime Polymorphism with Data Members

Runtime Polymorphism can't be achieved by data members in C#. Let's see the given example where you are accessing the field by reference variable which refers to the instance of the derived class.

using System;  

public class Color{
    public string ColorName = "Red";
}
public class Cat: Color
{
    public string color = "Green";
}
public class SealedExample
{
    public static void Main()
    {
        Color obj = new Cat();
        Console.WriteLine(obj.ColorName);
    }
}  

Output

Red