views:

152

answers:

2

If I have a method with a using block like this...

    public IEnumerable<Person> GetPersons()
    {
        using (var context = new linqAssignmentsDataContext())
        {
            return context.Persons.Where(p => p.LastName.Contans("dahl"));
        }
    }

...that returns the value from within the using block, does the IDisposable object still get disposed?

+16  A: 

Yes it does. The disposing of the object occurs in a finally block which executes even in the face of a return call. It essentially expands out to the following code

var context = new linqAssignmentsDataContext();
try {
  return context.Persons.Where(p => p.LastName.Contans("dahl"));
} finally {
  if ( context != null ) {
    context.Dispose();
  }
}
JaredPar
+2  A: 

From the MSDN documentation:

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.

So the object is always disposed. Unless you plug out the power cable.

AndiDog
"So the object is always disposed. Unless you plug out the power cable." - In which case, the object is disposed as the electrons disperse ;-)
Nick
Reminds me to this TheDailyWTF article (the first one): http://thedailywtf.com/Articles/My-Tales.aspx
DrJokepu
Calling Environment.FailFast will also not call Dispose in addition to pulling the power cable.
Robert Davis
Robert Davis: In .NET, a stack overflow shuts downs the process as well without executing finally blocks.
DrJokepu
Yes, it was just an example. And by the time I wrote that answer, I thought about the TheDailyWTF article, too... ;)
AndiDog