Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jump to finally without calling return

Tags:

c#

In C# (when using a try / finally) how can I jump to the finally section without calling return.

For example:

public bool SomeMethod()
{
    try
    {
        ...
        if (...)
        {
            ---> Jump to finally
        }
        else
        {
            ...
        }

        ...

        if (...)
        {
            ---> Jump to finally
        }
        else
        {
            ...
        }
        ...
        return true;
    }
    finally
    {
        ...

        if (...)
            return true;
        else
            return false;
    }

}

How can I force a jump to the finally section (without using return)?

Edit:

What I'm trying to do is:

public bool SomeMethod(ref string Error)
{
    try
    {
        bool result = false;

        if (...)
            ---> Exit to Finally
        else
            ...

        ...

        if (...)
            ---> Exit to Finally
        else
            ...

        ...

        --> more of the above kind of IFs

        return true;
    }
    finally
    {
        ...

        if (!result)
        {
                LogAMessage("");
                ...
                Error = "...";
                ...
        }
        return result;
    }

}
like image 359
mas Avatar asked Nov 29 '11 13:11

mas


1 Answers

You could use a label and goto.

However, this seems to suggest that your function is probably not structured well.

In this case, you seem to be using finally as a function - why not extract that logic into a function of its own?

like image 153
Oded Avatar answered Oct 03 '22 06:10

Oded