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

Base class and derived class in C Sharp (C#) - Time & Space Complexity

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

Scenario Under Consideration

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

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

As the number of animals grows, the number of Speak() calls grows the same way.

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

Pattern observation: The work grows directly with the number of animals.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as you add more animals.

Common Mistake

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

Interview Connect

Understanding how method calls scale with object count helps you explain performance clearly and confidently in interviews.

Self-Check

"What if we added a nested loop inside the Speak() method? How would the time complexity change?"