Action delegate type in C Sharp (C#) - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Calling the Action delegate inside a for loop.
- How many times: The loop runs exactly
counttimes, so the delegate is calledcounttimes.
As the input count grows, the number of times the delegate runs grows the same way.
| Input Size (count) | Approx. Operations |
|---|---|
| 10 | 10 calls to the Action delegate |
| 100 | 100 calls to the Action delegate |
| 1000 | 1000 calls to the Action delegate |
Pattern observation: The total work grows directly with the input size. Double the input, double the calls.
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.
[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.
Understanding how delegates affect time helps you explain how your code scales when using callbacks or events, a common real-world skill.
"What if the Action delegate itself contains a loop that runs n times? How would the time complexity change?"