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

Suppose you have a C # method with an operator returninside a block try. Is it possible to change the return value in a block finally?

An obvious approach, using returnin a block finallywill not 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: returninternally it is finallyforbidden, but we can abuse the fact that (perhaps for reasons of backward compatibility) VB still allows you to change the return value by assigning its method name:

Function Foo() As String    ' Returns "B", really!
    Try
        Return "A"
    Finally
        Foo = "B"
    End Try
End Function

Notes:

  • Please note that I ask this question solely out of scientific curiosity; obviously, such code is very error prone and confusing and should never be written.

  • , try { var x = "A"; return x; } finally { x = "B"; }. , , , . , , try, finally.

+5
4

, # return try. finally?

.

finally:

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

, " 123" , 123, , . 456.

+18

VB.NET VB6, , .

, IL, return, myFunc = "B", try...catch...finally, , , , return.

0

To achieve the same effect, you can do the following:

private string myFunction()
{
    string result = String.Empty;
    try
    {
        //..
        result = "something";
    }
    finally
    {
        result = "something else";
    }
    return result;
}
-1
source

A close analogy to the VB approach cited will assign a revised value to the variable used return(which has the advantage of retaining a single control return point):

string returnResult;

try
{
    returnResult = "A";
}
finally
{
    returnResult = "B";
}

return returnResult;
-1
source

All Articles