Is it a good approach to call return inside using {} statement?

user240141 picture user240141 · Aug 2, 2012 · Viewed 34.2k times · Source

I just want to know is it safe/ good approach to call return inside a using block.

For ex.

using(var scope = new TransactionScope())
{
  // my core logic
  return true; // if condition met else
  return false;
  scope.Complete();
}

We know the at the last most curly brace dispose() will get called off. But what will be in the above case, since return jumps the control out of the given scope (AFAIK)...

  1. Is my scope.Complete() get called?
  2. And so for the scope's dispose() method.

Answer

Øyvind Bråthen picture Øyvind Bråthen · Aug 2, 2012

It's perfectly safe to call return inside your using block, since a using block is just a try/finally block.

In your example above after return true, the scope will get disposed and the value returned. return false, and scope.Complete() will not get called. Dispose however will be called regardless since it reside inside the finally block.

Your code is essentially the same as this (if that makes it easier to understand):

var scope = new TransactionScope())
try
{
  // my core logic
  return true; // if condition met else
  return false;
  scope.Complete();
}
finally
{
  if( scope != null) 
    ((IDisposable)scope).Dispose();
}

Please be aware that your transaction will never commit as there's no way to get to scope.Complete() to commit the transaction.