Runtime polymorphism execution in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time it takes to run a program changes when using runtime polymorphism in C#.
Specifically, we ask: How does calling methods through polymorphism affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
using System;
class Animal {
public virtual void Speak() {
Console.WriteLine("Animal speaks");
}
}
class Dog : Animal {
public override void Speak() {
Console.WriteLine("Dog barks");
}
}
void MakeAnimalsSpeak(Animal[] animals) {
foreach (var animal in animals) {
animal.Speak();
}
}
This code calls the Speak method on each Animal object, using runtime polymorphism to decide which Speak version to run.
- Primary operation: The loop that calls
Speak()on each animal in the array. - How many times: Once for each animal in the input array.
Each animal in the array causes one method call. The program does a little extra work to find the right method at runtime.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 method calls with runtime checks |
| 100 | About 100 method calls with runtime checks |
| 1000 | About 1000 method calls with runtime checks |
Pattern observation: The number of operations grows directly with the number of animals. Each call has a small extra cost for deciding which method to run.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of animals, even with runtime polymorphism.
[X] Wrong: "Runtime polymorphism makes the program run much slower, like quadratic time."
[OK] Correct: Each method call still happens once per item, with only a small extra step to find the right method. It does not multiply calls or loops.
Understanding how runtime polymorphism affects performance shows you know how programs decide what to do while running. This skill helps you write clear and efficient code.
"What if we replaced the array with a nested loop calling Speak on each animal multiple times? How would the time complexity change?"
Practice
Solution
Step 1: Understand runtime polymorphism concept
Runtime polymorphism allows a base class reference to call methods overridden in derived classes.Step 2: Identify correct behavior
This means the actual method called depends on the object's real type, not the reference type.Final Answer:
Call derived class methods through a base class reference -> Option CQuick Check:
Runtime polymorphism = base ref calls derived method [OK]
- Confusing polymorphism with changing variable types
- Thinking static methods are polymorphic
- Believing polymorphism creates multiple instances
Solution
Step 1: Identify keyword to enable overriding
The base class method must be marked withvirtualto allow overriding.Step 2: Understand roles of keywords
overrideis used in derived classes,virtualin base classes.Final Answer:
virtual -> Option AQuick Check:
Base method uses virtual to allow override [OK]
- Using override in base class instead of virtual
- Confusing new keyword with override
- Thinking abstract is required for all overrides
class Animal {
public virtual string Speak() => "Animal sound";
}
class Dog : Animal {
public override string Speak() => "Bark";
}
class Cat : Animal {
public override string Speak() => "Meow";
}
Animal a = new Dog();
Console.WriteLine(a.Speak());Solution
Step 1: Identify object type and method called
Variableais of typeAnimalbut references aDogobject.Step 2: Apply runtime polymorphism
SinceSpeakis virtual and overridden inDog, theDogversion runs, printing "Bark".Final Answer:
Bark -> Option BQuick Check:
Base ref calls Dog's Speak() = Bark [OK]
- Expecting base class method output
- Confusing object type with reference type
- Thinking compile error due to override
class Base {
public override void Show() {
Console.WriteLine("Base Show");
}
}
class Derived : Base {
public override void Show() {
Console.WriteLine("Derived Show");
}
}Solution
Step 1: Check base class method declaration
Base class method incorrectly usesoverrideinstead ofvirtual.Step 2: Understand override rules
Only derived classes useoverride; base class must usevirtualto allow overriding.Final Answer:
Base class method must be virtual, not override -> Option AQuick Check:
Base method needs virtual keyword [OK]
- Using override in base class method
- Thinking override is allowed without virtual
- Ignoring method signature correctness
class Vehicle {
public virtual string Describe() => "Vehicle";
}
class Car : Vehicle {
public override string Describe() => "Car";
}
class SportsCar : Car {
public override string Describe() => "SportsCar";
}
Vehicle v = new SportsCar();
Car c = new SportsCar();
SportsCar s = new SportsCar();
Console.WriteLine(v.Describe());
Console.WriteLine(c.Describe());
Console.WriteLine(s.Describe());
What is the output?Solution
Step 1: Identify actual object type for all references
All variablesv,c, andsreference aSportsCarobject.Step 2: Apply runtime polymorphism for Describe()
SinceDescribeis overridden inSportsCar, all calls print "SportsCar" regardless of reference type.Final Answer:
SportsCar\nSportsCar\nSportsCar -> Option DQuick Check:
All calls use SportsCar override [OK]
- Assuming base class method runs for base type variable
- Confusing reference type with object type
- Ignoring override in most derived class
