All, this is a simple one. Is there a way of testing the returned value within a finally
block without doing
bool result = false;
try
{
if (someCondition)
{
result = true;
return result;
}
return result;
}
finally
{
if (result)
// Do something mind-blowing.
}
Do I have to use the variable result
of is there a cleaner way?
Note: I am aware that this is not a lot of work to do what i am doing now. I am curious for intricacies of the .NET world.
The short answer is: No. That is not possible. I'm thinking that you are mostly interested in a good readability for your code.
Sometimes you actually need a reference to other variables in the finally block, even when your function is returning something.
For example if you're using some IDisposable implementations and you do not want or cannot (in order to preserve readability) use using
blocks, then you need to Dispose()
them in the finally
block.
So, having the extra declaration is not a big deal, especially if it's only one. The code is still readable.
For multiple and nested try/catch statements, a good design decision would be to put each try/catch block with all logic related to it in a separate function which returns true/false or a result that is useful in the caller's context.