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

Delegates as callback pattern in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Delegates as callback pattern
O(n)
Understanding Time Complexity

When using delegates as callbacks, it is important to understand how the program's running time changes as the input grows.

We want to know how many times the callback runs and how that affects overall execution time.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


public delegate void Callback(int value);

public void ProcessItems(int[] items, Callback callback)
{
    foreach (var item in items)
    {
        callback(item);
    }
}
    

This code runs a callback delegate on each item in an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The foreach loop that calls the callback for each item.
  • How many times: Once for every element in the input array.
How Execution Grows With Input

As the number of items grows, the callback runs more times, directly increasing total work.

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

Pattern observation: The work grows in a straight line with input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to the number of items.

Common Mistake

[X] Wrong: "The callback runs only once, so time is constant regardless of input size."

[OK] Correct: The callback runs once for each item, so more items mean more calls and more time.

Interview Connect

Understanding how callbacks affect time helps you explain how your code scales and shows you can reason about program efficiency.

Self-Check

"What if the callback itself contains a loop over the entire array? How would the time complexity change?"