Implementing interfaces in C Sharp (C#) - Time & Space Complexity
When we implement interfaces in C#, we write code that follows a set of rules. It's important to understand how the time it takes to run this code changes as the input grows.
We want to know: how does the program's work increase when we use interfaces?
Analyze the time complexity of the following code snippet.
interface IPrinter
{
void Print(string message);
}
class ConsolePrinter : IPrinter
{
public void Print(string message)
{
for (int i = 0; i < message.Length; i++)
{
System.Console.Write(message[i]);
}
System.Console.WriteLine();
}
}
This code defines an interface with a print method and a class that implements it by printing each character of a message one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each character in the message string.
- How many times: It runs once for every character in the message, so as many times as the message length.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character prints |
| 100 | About 100 character prints |
| 1000 | About 1000 character prints |
Pattern observation: The work grows directly with the length of the message. Double the message length, double the work.
Time Complexity: O(n)
This means the time to print grows in a straight line with the message length.
[X] Wrong: "Implementing an interface adds extra hidden loops or slows down the code a lot."
[OK] Correct: Implementing an interface itself does not add loops or slow down the code. The time depends on what the methods do, not on the interface structure.
Understanding how your code runs when using interfaces shows you can write clean, flexible programs without losing track of performance. This skill helps you explain your code clearly and confidently.
"What if the Print method used recursion instead of a loop? How would the time complexity change?"