Search code examples
c#returnusing

If a call to return is made in a using block, what is the order of operation behind the scenes?


Does the end of the using block get hit if a return is called inside of it? For example,

using( var ur = new UnmanagedResource() )
{
  if( SomeCondition == true ){
   return SomeReturnValue;
  }
}

When SomeCondition is true, will the UnmanagedResource be disposed from the end of the using block before the return is called? What is the order of operations behind the scenes that would take place in this scenario?


Solution

  • The object is disposed prior to the control flow returning to the caller of the method.

    This is detailed in the C# language specification, section 8.9:

    Execution of jump statements is complicated by the presence of intervening try statements. In the absence of such try statements, a jump statement unconditionally transfers control from the jump statement to its target. In the presence of such intervening try statements, execution is more complex. If the jump statement exits one or more try blocks with associated finally blocks, control is initially transferred to the finally block of the innermost try statement. When and if control reaches the end point of a finally block, control is transferred to the finally block of the next enclosing try statement. This process is repeated until the finally blocks of all intervening try statements have been executed.

    ...

    finally blocks associated with two try statements are executed before control is transferred to the target of the jump statement.

    Since a using statement is turned into a try/finally (detailed in 8.13), this means the Dispose call is guaranteed to occur "prior to the return" (rather, prior to control flow jumping to the caller of this method), as return is a "jump statement".