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

Action delegate type in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Action delegate type
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code using the Action delegate changes as the input grows.

How does the number of times the delegate runs affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


Action printNumber = n => Console.WriteLine(n);

void RunActionMultipleTimes(int count, Action action)
{
    for (int i = 0; i < count; i++)
    {
        action(i);
    }
}

RunActionMultipleTimes(5, printNumber);
    

This code runs an Action delegate multiple times, printing numbers from 0 up to count - 1.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the Action delegate inside a for loop.
  • How many times: The loop runs exactly count times, so the delegate is called count times.
How Execution Grows With Input

As the input count grows, the number of times the delegate runs grows the same way.

Input Size (count)Approx. Operations
1010 calls to the Action delegate
100100 calls to the Action delegate
10001000 calls to the Action delegate

Pattern observation: The total work grows directly with the input size. Double the input, double the calls.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line with the number of times the Action delegate is called.

Common Mistake

[X] Wrong: "Calling an Action delegate inside a loop is instant and does not add to time."

[OK] Correct: Each call to the delegate runs code and takes time, so more calls mean more total time.

Interview Connect

Understanding how delegates affect time helps you explain how your code scales when using callbacks or events, a common real-world skill.

Self-Check

"What if the Action delegate itself contains a loop that runs n times? How would the time complexity change?"