0

I'm using entity framework in my MVC website and I'm disposing my database context using using-statement. Now my question is if I close using statement after return, would the database context disposed properly or not. Ex:

 public ActionResult SomeAction(){

      using (var DB = new DatabaseContext()){

       ....           

       return View();                
      }
 }

Do I have to close the using statement before return? Or it would be disposed properly in the way I'm using it.

2

1 Answer 1

1

Do I have to close the using statement before return? Or it would be disposed properly in the way I'm using it?

It will be automagically disposed for you. You can refer to this answer for more information .The Dispose method is called however the using statement is executed, unless it was an abrupt whole-process termination. The most common cases are:

  • A return within the block
  • An exception being thrown (and not caught) within the block
  • Reaching the end of the block naturally

Basically a using statement is mostly syntactic sugar for a try/finally block - and finally has all the same properties.

From section 8.13 of the C# 4 specification:

A using statement is stranslated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource.

Sign up to request clarification or add additional context in comments.

1 Comment

Based on your common cases if we have return within using statement it won't be disposed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.