Runtime polymorphism lets a program decide which method to run while it is running, not before. This helps make programs flexible and easy to change.
Runtime polymorphism execution in C Sharp (C#)
class BaseClass { public virtual void Show() { // base method } } class DerivedClass : BaseClass { public override void Show() { // derived method } } BaseClass obj = new DerivedClass(); obj.Show();
virtual keyword marks a method that can be changed in child classes.
override keyword is used in child classes to provide a new version of the method.
Speak method is called on an Animal reference but runs the Dog version because of runtime polymorphism.class Animal { public virtual void Speak() { Console.WriteLine("Animal speaks"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Dog barks"); } } Animal pet = new Dog(); pet.Speak();
Draw method runs the Circle version even though the variable is of type Shape.class Shape { public virtual void Draw() { Console.WriteLine("Drawing shape"); } } class Circle : Shape { public override void Draw() { Console.WriteLine("Drawing circle"); } } Shape s = new Circle(); s.Draw();
This program shows runtime polymorphism by calling the Start method on a Vehicle reference that points to different types of vehicles. The actual method that runs depends on the object type at runtime.
using System; class Vehicle { public virtual void Start() { Console.WriteLine("Vehicle is starting"); } } class Car : Vehicle { public override void Start() { Console.WriteLine("Car is starting with a roar"); } } class Bike : Vehicle { public override void Start() { Console.WriteLine("Bike is starting quietly"); } } class Program { static void Main() { Vehicle myVehicle; myVehicle = new Car(); myVehicle.Start(); myVehicle = new Bike(); myVehicle.Start(); } }
Runtime polymorphism requires a base method marked with virtual and derived methods marked with override.
The decision about which method to call happens when the program runs, not when it is compiled.
Using runtime polymorphism helps keep code easy to extend and maintain.
Runtime polymorphism lets methods behave differently based on the actual object type at runtime.
Use virtual in base classes and override in derived classes to enable this behavior.
This makes your code flexible and easier to change later.