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!
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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With