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

Default interface methods in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default interface methods
O(n)
Understanding Time Complexity

When using default interface methods in C#, it's important to understand how the program's running time changes as input grows.

We want to see how calling these methods affects the total work done by the program.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


interface IPrinter
{
    void Print();
    void PrintMultiple(int times)
    {
        for (int i = 0; i < times; i++)
            Print();
    }
}

class ConsolePrinter : IPrinter
{
    public void Print() => Console.WriteLine("Hello");
}

// Usage
IPrinter printer = new ConsolePrinter();
printer.PrintMultiple(5);
    

This code defines an interface with a default method that calls another method multiple times. The class implements the interface and the default method is used to print a message repeatedly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop inside the default method PrintMultiple that calls Print repeatedly.
  • How many times: The loop runs times times, which depends on the input parameter.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (times)Approx. Operations (Print calls)
1010
100100
10001000

Pattern observation: The number of print calls grows directly with the input number times. If you double times, the work doubles.

Final Time Complexity

Time Complexity: O(n)

This means the time to run PrintMultiple grows linearly with the number of times you want to print.

Common Mistake

[X] Wrong: "Default interface methods run instantly and don't add to execution time."

[OK] Correct: Even though the method is defined in the interface, it still runs its code each time it's called, so the loop inside causes repeated work proportional to the input.

Interview Connect

Understanding how default interface methods behave helps you reason about code performance and design choices, a useful skill in real projects and interviews.

Self-Check

"What if the default method called another default method inside the interface that also loops? How would the time complexity change?"