Assume that you have a C# method with a return
statement inside a try
block. Is it possible to modify the return value in the finally
block?
The obvious approach, using return
in the finally
block, won't work:
String Foo()
{
try
{
return "A";
}
finally
{
// Does not compile: "Control cannot leave the body of a finally clause"
return "B";
}
}
Interestingly, this can be done in VB: Return
inside Finally
is forbidden, but we can abuse the fact that (probably for reasons of backwards compatibility) VB still allows the return value to be modified by assigning it to the method name:
Function Foo() As String ' Returns "B", really!
Try
Return "A"
Finally
Foo = "B"
End Try
End Function
Notes:
Note that I ask this question purely out of scientific curiosity; obviously, code like that is highly error-prone and confusing and should never be written.
Note that I am not asking about
try { var x = "A"; return x; } finally { x = "B"; }
. I am aware that this doesn't change the return value and I understand why this happens. I'd like to know if there are ways to change the return value set inside the try block by means of a finally block.