Testing the Return Value Within the Finally Block
-
16-06-2021 - |
Question
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.
Solution
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.
OTHER TIPS
if it was me I'd have an other variable to indicate something was required in the finally block.
You mention SqlConnection in another comment so it could be you do
if (myConnection != null) { myConnection.Dispose(); }
though the pukka .net way would have had the connection in a using block, so finally wouldn't be required to get rid of it.
If you want to stick with result then
bool result = false;
try
{
if (someCondition)
{
result = true;
}
}
finally
{
if (result) // Do something mind-blowing.
}
return result;
Would make more sense to me, though perhaps not to others....
Since C# has no equivalent of D's scope, you are pretty much consigned to try..finally
.
See also: D Exception Safety.