Problem
Something like:
using (IDisposable disposable = GetSomeDisposable())
{
//.....
//......
return Stg();
}
I don’t think it’s the right location for a return statement, is it?
Asked by tafa
Solution #1
As countless others have stated, this is not a problem in general.
Only if you return in the middle of a using statement and also return the in using variable will you run into problems. However, even if you didn’t return and only preserved a reference to a variable, this would pose problems.
using ( var x = new Something() ) {
// not a good idea
return x;
}
Just as bad
Something y;
using ( var x = new Something() ) {
y = x;
}
Answered by JaredPar
Solution #2
It’s perfectly fine.
Assume you believe this.
using (IDisposable disposable = GetSomeDisposable())
{
//.....
//......
return Stg();
}
is interpreted literally as:
IDisposable disposable = GetSomeDisposable()
//.....
//......
return Stg();
disposable.Dispose();
Which, admittedly, would be an issue and render the using statement useless —- which is why it doesn’t do that.
Regardless of how control leaves the block, the compiler ensures that the object is disposed of before control leaves.
Answered by James Curran
Solution #3
It’s just alright; there’s no issue. What makes you think it’s a bad idea?
A using statement is just syntactic sugar for a try/finally block, and returning from a try block is fine, too, as Grzenio points out.
The method will return after the return expression has been evaluated, the finally block has been executed, and the method has been executed.
Answered by Jon Skeet
Solution #4
This will work great, just like returning to tryfinally in the middle of the game.
Answered by Grzenio
Solution #5
That’s perfectly acceptable. A using statement guarantees that the IDisposable object will be disposed regardless of what happens.
From MSDN:
Answered by mbillard
Post is based on https://stackoverflow.com/questions/662773/returning-in-the-middle-of-a-using-block