Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when 'return' is called from within a 'using' block? [duplicate]

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?

like image 882
Byron Sommardahl Avatar asked Feb 17 '10 22:02

Byron Sommardahl


2 Answers

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();
  }
}
like image 127
JaredPar Avatar answered Oct 27 '22 23:10

JaredPar


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.

like image 35
AndiDog Avatar answered Oct 28 '22 01:10

AndiDog