开发者

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

开发者 https://www.devze.com 2022-12-20 17:23 出处:网络
This question already has answers here: returning in the middle of a using block (7 answers) 开发者_高级运维Closed 9 years ago.
This question already has answers here: returning in the middle of a using block (7 answers) 开发者_高级运维 Closed 9 years ago.

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?


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();
  }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消