Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from a using statement

Tags:

c#

I am trying to exit from a using statement while staying in an enclosing for loop. eg.

 for (int i = _from; i <= _to; i++)
 {

    try
    {

        using (TransactionScope scope = new TransactionScope())
        {
            if (condition is true)
            {
                // I want to quit the using clause and
                // go to line marked //x below
                // using break or return drop me to line //y
                // outside of the for loop.
            }

        }

    } //x
}
//y

I have tried using break which spits me out at //y, however I want to remain in the for loop at //x so the for loop continues to process. I know that I can do it by throwing an exception and using a catch but I'd rather not do this relatively expensive operation if there is a more elegant way to break out of the using. Thanks!

like image 481
Tim Newton Avatar asked May 16 '13 14:05

Tim Newton


2 Answers

You are able to use a label, and use goto label to jump out of the using(() statement.

using (var scope = _services.CreateScope())
{
    if (condition) {
        goto finished;
    }
}

finished:
// continue operation here
like image 139
Roy vd Wijk Avatar answered Sep 25 '22 00:09

Roy vd Wijk


There is no need to break out of a using block because a using block does not loop. You can simply fall through to the end. If there is code you don't want to execute, skip it using an if-clause.

    using (TransactionScope scope = new TransactionScope())
    {
        if (condition)
        {
            // all your code that is executed only on condition
        }
    }
like image 30
nvoigt Avatar answered Sep 25 '22 00:09

nvoigt