C Sharp Polymorphism

C# Polymorphism

Being a combination of “poly” and “morphs”, the term “Polymorphism” is a Greek word that means many forms. The principal concepts of an object-oriented programming language are an inheritance, encapsulation, and polymorphism. C# supports two types of polymorphism: compile time polymorphism and runtime polymorphism.

Compile-time polymorphism:

Method overloading and operator overloading are used to achieve Compile-time polymorphism ( also known as static binding or early binding) in C#.

Runtime polymorphism:

Method overriding is used to achieve Runtime Polymorphism ( also known as dynamic binding or late binding) in C#.

Example 1:

using System;  
public class Flower{  
    public virtual void color(){  
        Console.WriteLine("White!!");  
    }  
}  
public class Lily: Flower  
{  
    public override void color()  
    {  
        Console.WriteLine("White Lily!!");  
    }  
 
}  
public class flwr  
{  
    public static void Main()  
    {  
        Flower a= new Lily();  
        a.color();  
    }  
}

Output:

Explanation:

In the above example, we are displaying the simple use and behavior of runtime polymorphism in C#.

Example 2:

using System;  
public class Flower{  
    public virtual void color(){  
        Console.WriteLine("White!!");  
    }  
}  
public class Rose: Flower  
{  
    public override void color()  
    {  
        Console.WriteLine("White Rose!!");  
    }  
 
}  
public class Lily : Flower  
{  
    public override void color()  
    {  
        Console.WriteLine("White Lily!!");  
    }  
 
}  
public class flwr  
{  
    public static void Main()  
    {  
        Flower f;  
        f = new Flower();  
        f.color();  
        f = new Rose();  
        f.color();  
        f = new Lily();  
        f.color();  
 
    }  
}

Output:

Explanation:

In the above example, we are displaying the use and behavior of runtime polymorphism in C# where we are having two derived classes.

Runtime Polymorphism with Data Members:

In C#, data members can’t achieve the Runtime Polymorphism.

Example:

using System;  
public class Flower{  
    public string color = "Red";  
 
}  
public class Lily: Flower  
{  
    public string color = "White";  
}  
public class flwr  
{  
    public static void Main()  
    {  
        Flower d = new Lily();  
        Console.WriteLine(d.color);  
 
    }  
}

Output:

Explanation:

In the above example, we are accessing the field by reference variable referring to the instance of the derived class.