views:

93

answers:

4

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?

+7  A: 

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.

SLaks
Thank you :)I was scared that my code would be made fun of
Snoop Dogg
Finally block doesn't *always* execute ;) http://thedailywtf.com/Comments/My-Tales.aspx
R0MANARMY
Uhm ok yeap. I clicked :)
Snoop Dogg
+3  A: 

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

Nagg
+1  A: 

Nope, the using block will force the firing of the Dispose object.

http://www.devx.com/dotnet/Article/33167

http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx

Kevin
+1  A: 

Your using statement will indeed succeed. It is akin to the following (which is what the C# compiler will translate the using statement into:

Entities db = new Entities();
try
{
    return db.TableName.AsQueryable().ToList();
}
finally
{
    ((IDisposable)db).Dispose();
}
jrista