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

Abstract classes and methods in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Abstract classes and methods
O(n)
Understanding Time Complexity

When using abstract classes and methods, it's important to understand how the program runs as input grows.

We want to know how the time to complete tasks changes when using these features.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

using System;
using System.Collections.Generic;

abstract class Animal
{
    public abstract void Speak();
}

class Dog : Animal
{
    public override void Speak() { Console.WriteLine("Woof"); }
}

class Program
{
    public static void MakeAnimalsSpeak(List<Animal> animals)
    {
        foreach (var animal in animals)
            animal.Speak();
    }
}

This code defines an abstract class with an abstract method, then calls that method on a list of animals.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The foreach loop calling Speak() on each animal.
  • How many times: Once for each animal in the list (n times).
How Execution Grows With Input

Each animal in the list causes one call to Speak(). So, as the list grows, the work grows evenly.

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

Pattern observation: The number of operations 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 with the number of animals.

Common Mistake

[X] Wrong: "Using abstract methods makes the program slower in a way that changes the time complexity."

[OK] Correct: Calling abstract methods adds a tiny fixed cost, but the overall time still grows linearly with input size.

Interview Connect

Understanding how abstract classes affect performance shows you grasp both design and efficiency, a useful skill in real projects and interviews.

Self-Check

"What if the Speak() method itself contained a loop over a list? How would that change the time complexity?"