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

Interface as contract mental model in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Interface as contract mental model
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Calling the Work() method on each worker object.
  • How many times: Once for each worker in the list.
How Execution Grows With Input

As the number of workers grows, the total calls to Work() grow the same way.

Input Size (n)Approx. Operations
1010 calls to Work()
100100 calls to Work()
10001000 calls to Work()

Pattern observation: The number of operations grows directly with the number of workers.

Final Time Complexity

Time Complexity: O(n)

This means the time to process all workers grows in a straight line as you add more workers.

Common Mistake

[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.

Interview Connect

Understanding how interfaces affect time helps you explain how your code scales when many objects follow the same contract.

Self-Check

"What if the Work() method itself contains a loop over a large list? How would that change the time complexity?"