returning in the middle of a using block

tafa picture tafa · Mar 19, 2009 · Viewed 49.9k times · Source

Something like:

using (IDisposable disposable = GetSomeDisposable())
{
    //.....
    //......
    return Stg();
}

I believe it is not a proper place for a return statement, is it?

Answer

JaredPar picture JaredPar · Mar 19, 2009

As several others have pointed out in general this is not a problem.

The only case it will cause you issues is if you return in the middle of a using statement and additionally return the in using variable. But then again, this would also cause you issues even if you didn't return and simply kept a reference to a variable.

using ( var x = new Something() ) { 
  // not a good idea
  return x;
}

Just as bad

Something y;
using ( var x = new Something() ) {
  y = x;
}