Interface as contract mental model in C Sharp (C#) - Time & Space Complexity
When we use interfaces as contracts in C#, we want to know how the program's speed changes as we add more objects that follow the interface.
We ask: How does the time to run methods grow when many objects implement the same interface?
Analyze the time complexity of the following code snippet.
interface IWorker
{
void Work();
}
class Worker : IWorker
{
public void Work() { /* do some work */ }
}
void ProcessWorkers(List workers)
{
foreach (var worker in workers)
worker.Work();
}
This code calls the Work method on each object in a list that implements the IWorker interface.
- Primary operation: Calling the Work() method on each worker object.
- How many times: Once for each worker in the list.
As the number of workers grows, the total calls to Work() grow the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to Work() |
| 100 | 100 calls to Work() |
| 1000 | 1000 calls to Work() |
Pattern observation: The number of operations grows directly with the number of workers.
Time Complexity: O(n)
This means the time to process all workers grows in a straight line as you add more workers.
[X] Wrong: "Using an interface makes the code slower because of extra overhead."
[OK] Correct: Calling methods through an interface adds very little overhead, and the main time cost comes from how many times you call the method, not the interface itself.
Understanding how interfaces affect time helps you explain how your code scales when many objects follow the same contract.
"What if the Work() method itself contains a loop over a large list? How would that change the time complexity?"