Default interface methods in C Sharp (C#) - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside the default method
PrintMultiplethat callsPrintrepeatedly. - How many times: The loop runs
timestimes, which depends on the input parameter.
Explain the growth pattern intuitively.
| Input Size (times) | Approx. Operations (Print calls) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of print calls grows directly with the input number times. If you double times, the work doubles.
Time Complexity: O(n)
This means the time to run PrintMultiple grows linearly with the number of times you want to print.
[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.
Understanding how default interface methods behave helps you reason about code performance and design choices, a useful skill in real projects and interviews.
"What if the default method called another default method inside the interface that also loops? How would the time complexity change?"