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?
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:
…
Since a using statement is turned into a try/finally (detailed in 8.13), this means the
Disposecall 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”.