18

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?

Byron Sommardahl
  • 12,743
  • 15
  • 74
  • 131

2 Answers2

29

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
  • 733,204
  • 149
  • 1,241
  • 1,454
7

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
  • 68,631
  • 21
  • 159
  • 205
  • 13
    "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 Feb 17 '10 at 22:10
  • 1
    Reminds me to this TheDailyWTF article (the first one): http://thedailywtf.com/Articles/My-Tales.aspx – Tamas Czinege Feb 17 '10 at 22:17
  • 1
    Calling Environment.FailFast will also not call Dispose in addition to pulling the power cable. – Robert Davis Feb 17 '10 at 22:20
  • 1
    Robert Davis: In .NET, a stack overflow shuts downs the process as well without executing finally blocks. – Tamas Czinege Feb 17 '10 at 22:21
  • Yes, it was just an example. And by the time I wrote that answer, I thought about the TheDailyWTF article, too... ;) – AndiDog Feb 17 '10 at 22:29