How does the Using keyword work?

cjard

Well-known member
Joined
Apr 25, 2006
Messages
7,081
Programming Experience
10+
For example, when we do a database transaction, we:

VB.NET:
Using myTransaction as New Transactions.TransactionScope
 'multiple database updates
End Using

what is magical about Using?


on a further note, if I said:

Dim myTransaction as New Transactions.TransactionScope

would my database queries still go into a transaction? How? What is "Using" actually doing with the object i created? Is it causing the code that follows to interact with it, or does TransactionScope have some magical ability to have all code that follows, participate?
 
The End Using statement disposes of the resources under the Using block's control. Using block guarantees disposal of the (used) resources, no matter how you exit the block. It does this by calling the Dispose method of the resource.
 
This:
VB.NET:
Using myObject As New MyType
    '...
End Using
is just shorthandl for this:
VB.NET:
Dim myObject As New MyType

Try
    '...
Finally
    myObject.Dispose()
End Try
 
Interesting. Given that it is not particular to database transactions, i'm very curious to know how a transaction hooks into the data access subsystem to arrange all database work in its block, in a transaction.. but that is a separate question. THanks for the info, guys!
 
Back
Top