Base keyword behavior in C Sharp (C#) - Time & Space Complexity
Let's explore how using the base keyword affects the time it takes for a program to run.
We want to see how calling a base class method impacts performance as the program grows.
Analyze the time complexity of the following code snippet.
class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Base Display");
}
}
class DerivedClass : BaseClass
{
public override void Display()
{
base.Display();
Console.WriteLine("Derived Display");
}
}
// Usage
var obj = new DerivedClass();
obj.Display();
This code calls a method in the base class from the derived class using base.Display().
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
base.Display()once inside the overridden method. - How many times: Exactly once per call to
DerivedClass.Display().
Each time Display() is called on the derived object, it calls the base method once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to base method |
| 100 | 100 calls to base method |
| 1000 | 1000 calls to base method |
Pattern observation: The number of base method calls grows directly with the number of calls to the derived method.
Time Complexity: O(n)
This means the time to run grows in a straight line with how many times you call the method.
[X] Wrong: "Using base makes the method run slower exponentially."
[OK] Correct: Calling a base method just adds one extra step per call, so it grows evenly, not exponentially.
Understanding how base method calls affect performance helps you explain inheritance behavior clearly and confidently.
What if the base method itself called another method repeatedly? How would that change the time complexity?