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

When to use abstract vs concrete in C Sharp (C#) - Performance Comparison

Choose your learning style9 modes available
Time Complexity: When to use abstract vs concrete
O(n)
Understanding Time Complexity

We want to understand how choosing abstract or concrete classes affects the time your program takes to run.

Specifically, how does this choice impact the number of steps your program performs as it grows?

Scenario Under Consideration

Analyze the time complexity of this example using abstract and concrete classes.


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

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

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

This code uses an abstract class Animal with a Speak method, and a concrete class Dog that implements it. The program calls Speak on a list of animals.

Identify Repeating Operations

Look at what repeats when the program runs.

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

As the number of animals grows, the program calls Speak more times.

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 classes makes the program slower because of extra method calls."

[OK] Correct: The extra method call cost is very small and does not change how the total time grows with input size.

Interview Connect

Understanding when to use abstract versus concrete classes shows you can design clear, flexible code without hurting performance as your program grows.

Self-Check

What if we replaced the abstract class with interfaces? How would the time complexity change?