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 outputs "1". but the value of i is changed to 3 in finally block. Why wasn't the value of 'i' changed to 3?
Thank you,
Consider this code- I think the code explains what you are thinking, and how you can make what you think should happen actually happen:
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.
You have to remember that finally executes after everything else in the try and catch. Place the return statement after the try/catch/finally statement to have it return 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With