Finally try the secret

Consider

static void Main(string[] args) { Console.WriteLine(fun()); } static int fun() { int i = 0; try { i = 1; return i; } catch (Exception ex) { i = 2; return i; } finally { i = 3; } } 

The sample code displays "1". but the value i is replaced with 3 in the finally block. Why has the value of "i" not changed to 3?

Thanks,

+4
source share
5 answers

Consider this code - I think the code explains what you think, and how you can do what you think should happen, actually happens:

 static void Main(string[] args) { int counter = 0; Console.WriteLine(fun(ref counter)); // Prints 1 Console.WriteLine(counter); // Prints 3 } static int fun(ref int counter) { try { counter = 1; return counter; } finally { counter = 3; } } 

With this code, you return 1 from the method, but you also set the counter variable to 3, which you can access from outside the method.

+12
source

You must remember that finally it does the rest in try and catch. Place the return statement after the try / catch / finally statement so that it returns 3.

+7
source

I assume that if you use a reference type instead of a value type, you will get a different behavior.

+3
source

When you said "return i" ... C # puts this return value in a temporary storage area (memory), and then runs your finally code ... if the finally block could change this value, it will defeat the security / finalism of the finally block .

This is similar to the using statement with return inside ... "Disposal" will still happen AFTER return (so to speak).

+2
source

Finally, always executed

Your code is always executed completely, regardless of whether an exception has been thrown. So your code should be:

 try { i = 1; } catch { i = 2; } finally { i = 3; } return i; 

But in this trivial case, finally, the block will not make much sense. Because we will always return 3 no matter what happened before.

Finally, used to free resources

Block

finally should usually be used when you need to free some system resources allocated in a try block (i.e. open a database connection with read data in a try block and close it in finally )). Therefore, they will always be released regardless of whether there was an exception or not. In this case, it makes no sense to use a finally block.

+1
source

All Articles