Quick Links
C#-Polymorphism : The word polymorphism means “having many forms”.
Typically, polymorphism occurs when there is a hierarchy of classes and they are related through inheritance from a common base class.
C#-Polymorphism means that a call to a member method will cause a different implementation to be executed depending on the type of object that invokes the method.
Runtime C#-Polymorphism Example:
using System;
public class Animal{
public virtual void eat(){
Console.WriteLine("eating...");
}
}
public class Dog: Animal
{
public override void eat()
{
Console.WriteLine("eating bread...");
}
}
public class TestPolymorphism
{
public static void Main()
{
Animal a= new Dog();
a.eat();
}
}
* )Runtime Polymorphism with Data Members:
Runtime Polymorphism can’t be achieved by data members in C#. Let’s see an example where we are accessing the field by reference variable which refers to the instance of derived class.
using System;
public class Animal{
public string color = "white";
}
public class Dog: Animal
{
public string color = "black";
}
public class TestSealed
{
public static void Main()
{
Animal d = new Dog();
Console.WriteLine(d.color);
}
}
Recommended Posts: