Returning from the scope of 'using'?

I have a 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 "use", will the cleanup still be used?

+6
c #
source share
5 answers

Yes, and this is one of the big advantages of using it.

+24
source share

Yes. This is really the equivalent of a try/finally - and finally blocks are executed, however the try block is completed, whether through an exception, the return statement or simply reaches the end of the block.

+12
source share

Yes it will.

+3
source share

Yes, all instances of objects that were initialized by the resource collection part in the using statement will automatically call the Dispose() method.

+1
source share

Yes, he will be cleansed. I see this as a failed C # attempt to support the Resource Initialization pattern.

0
source share

All Articles