11

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?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Snoop Dogg
  • 335
  • 1
  • 4
  • 13

4 Answers4

16

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
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    Finally block doesn't *always* execute ;) http://thedailywtf.com/Comments/My-Tales.aspx – Roman Mar 29 '10 at 18:36
3

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

EgorBo
  • 6,120
  • 3
  • 35
  • 40
2

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
  • 32,447
  • 15
  • 90
  • 130
1

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

kemiller2002
  • 113,795
  • 27
  • 197
  • 251