0
0
C Sharp (C#)programming~5 mins

Base keyword behavior in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Base keyword behavior
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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().
How Execution Grows With Input

Each time Display() is called on the derived object, it calls the base method once.

Input Size (n)Approx. Operations
1010 calls to base method
100100 calls to base method
10001000 calls to base method

Pattern observation: The number of base method calls grows directly with the number of calls to the derived method.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with how many times you call the method.

Common Mistake

[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.

Interview Connect

Understanding how base method calls affect performance helps you explain inheritance behavior clearly and confidently.

Self-Check

What if the base method itself called another method repeatedly? How would that change the time complexity?