tags:

views:

220

answers:

5

I've got some code that looks like this:

using (DBDataContext dc = new DBDataContext(ConnectionString))
{
    Main main = new Main
    {
     ClientTime = clientTime
    };
    dc.Mains.InsertOnSubmit(main);
    dc.SubmitChanges();
    return main.ID;
}

If I return from inside a "using", will the using still clean up?

+23  A: 

Yes, and that's one of the big advantages of using it.

Otávio Décio
Mark this as the answer, as its 100% correct.
Will
tempted to -1 for the pun, but +1 all the same ;)
johnc
It's a recursive pun...
George Stocker
+3  A: 

Yes, it will.

+12  A: 

Yes. It really is just the equivalent of a try/finally statement - and finally blocks get executed however the try block exits, whether through an exception, a return statement, or just getting to the end of the block.

Jon Skeet
+1  A: 

Yes, all object instances that were initialized in the resource-acquisition part of the using statement will have their Dispose() method called automatically.

Kon
Only those objects which are specified within the resource-acquisition part of the using statement are disposed, and *nothing* special happens in terms of garbage collection.
Jon Skeet
@Jon, thanks.. I wasn't specific enough.. thus making my answer incorrect. Will fix.
Kon
@fallen888 - I changed it to reflect what Jon was saying, hope you don't mind
Greg Dean
A: 

Yes it will clean up. I see this as C#'s poor ass attempt to support the Resource Acquisition Is Initialization pattern.

Daniel Paull
RAII is unique to C++, because it is inherently based on C++'s unique stack-object construction/destruction features. C# borrowed the pattern from C++ because it proved useful, but had to modify the pattern, because stack-object construction/destruction does not work the same way as it does in C++.
Justice
@Justice - that's a long winded, but far more useful, version of "poor ass attempt".
Daniel Paull