views:

344

answers:

5

Something like:

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

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

+9  A: 

This will work perfectly fine, just as returning in the middle of try{}finally{}

Grzenio
+4  A: 

That is totally acceptable. A using statement ensures the IDisposable object will be disposed no matter what.

From MSDN:

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

GoodEnough
+3  A: 

It's absolutely fine - no problem at all. Why do you believe it's wrong?

A using statement is just syntactic sugar for a try/finally block, and as Grzenio says it's fine to return from a try block too.

The return expression will be evaluated, then the finally block will be executed, then the method will return.

Jon Skeet
James Curran's answer explains what I was thinking.
tafa
+1  A: 

It's perfectly fine.

You are apparently thinking that

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

is blindly translated into:

IDisposable disposable = GetSomeDisposable()
//.....
//......
return Stg();
disposable.Dispose();

Which, admittedly, would be a problem, and would make the using statement rather pointless --- which is why that's not what it does.

The compiler makes sure that the object is disposed before control leaves the block -- regardless of how it leaves the block.

James Curran
I was, apparently.
tafa
+5  A: 

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;
}
JaredPar
Just I was about to edit my question about the point you mentioned. Thanks.
tafa