Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET using block and return; keyword

When I say this

using (Entities db = new Entities())
{
    return db.TableName.AsQueryable().ToList();
}

Do I by-pass the functionality of using block since I return something, and the method exits before exiting the using block, so I think the using block will not serve to its purpose and dispose the resource.

Is this correct?

like image 756
Snoop Dogg Avatar asked Mar 29 '10 18:03

Snoop Dogg


2 Answers

You are incorrect; it will be disposed.

The using statement compiles to a try / finally block that disposes the original object in the finally block.
finally blocks are always executed, even if the code inside the try block returned a value or threw an exception.

like image 190
SLaks Avatar answered Nov 10 '22 00:11

SLaks


using statement will call Dispose of db object before value returning.

like image 3
Nagg Avatar answered Nov 09 '22 23:11

Nagg