Search code examples
c#disposeidisposableusing-statement

returning in the middle of a using block


Something like:

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

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


Solution

  • 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;
    }