Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change the return value in a finally clause in C#?

Tags:

c#

return

vb.net

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:

  1. 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.

  2. 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.

like image 595
Heinzi Avatar asked Apr 16 '13 14:04

Heinzi


1 Answers

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?

No.

You can however modify the return value outside the finally block:

static int M()
{
    try
    {
        try
        { 
            return 123;
        }
        finally
        {
            throw new Exception();
        }
    }
    catch
    {
        return 456;
    }
}

Just because there was originally a "return 123" does not mean that the method will return 123, if that's what your question is actually getting at. This method returns 456.

like image 186
Eric Lippert Avatar answered Sep 28 '22 01:09

Eric Lippert