Finally block behavior in C Sharp (C#) - Time & Space Complexity
We want to understand how the finally block affects the running time of a program.
Does it add extra repeated work or change how long the program takes as input grows?
Analyze the time complexity of the following code snippet.
try
{
for (int i = 0; i < n; i++)
{
Console.WriteLine(i);
}
}
finally
{
Console.WriteLine("Cleanup done.");
}
This code prints numbers from 0 to n-1, then always prints a cleanup message.
- Primary operation: The
forloop printing numbers from 0 to n-1. - How many times: Exactly n times, once per number.
- Finally block operation: Runs once after the try block finishes, printing a single message.
As n grows, the loop runs more times, but the finally block runs only once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints + 1 cleanup print = 11 |
| 100 | 100 prints + 1 cleanup print = 101 |
| 1000 | 1000 prints + 1 cleanup print = 1001 |
Pattern observation: The total work grows mostly with n, the finally block adds a fixed small cost.
Time Complexity: O(n)
This means the program's running time grows linearly with the input size, and the finally block does not change that.
[X] Wrong: "The finally block runs multiple times and adds to the loop's cost."
[OK] Correct: The finally block runs only once after the try block finishes, so it adds a fixed cost, not a repeated one.
Understanding how finally blocks behave helps you reason about program flow and performance clearly, a useful skill in many coding situations.
"What if the finally block contained a loop that also runs n times? How would the time complexity change?"