Base class and derived class in C Sharp (C#) - Time & Space Complexity
When using base and derived classes, it's important to see how the program runs as the number of objects grows.
We want to know how the time to run changes when we create and use many objects from these classes.
Analyze the time complexity of the following code snippet.
class Animal {
public virtual void Speak() {
Console.WriteLine("Animal speaks");
}
}
class Dog : Animal {
public override void Speak() {
Console.WriteLine("Dog barks");
}
}
void MakeAnimalsSpeak(List<Animal> animals) {
foreach (var animal in animals) {
animal.Speak();
}
}
This code defines a base class and a derived class, then calls a method on each object in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the Speak() method on each animal in the list.
- How many times: Once for each animal in the list, so as many times as the list size.
As the number of animals grows, the number of Speak() calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to Speak() |
| 100 | 100 calls to Speak() |
| 1000 | 1000 calls to Speak() |
Pattern observation: The work grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line as you add more animals.
[X] Wrong: "Because of inheritance, calling methods on derived classes is slower and adds extra loops."
[OK] Correct: Calling overridden methods still happens once per object, just like calling any method. Inheritance does not add hidden loops.
Understanding how method calls scale with object count helps you explain performance clearly and confidently in interviews.
"What if we added a nested loop inside the Speak() method? How would the time complexity change?"