- In the past...
- Employing the using Statement
- Using the TransactionScope
- Summary
Employing the using Statement
The keyword using now exists in both C# and VB. Using implicitly establishes a try..finally block and ensures that anything created in the using statement has its Dispose method called.
Thus, to use using, such as was done in Listing 1, the object created must implement IDisposable. In Listing 1 the SqlConnection’s Dispose method is called. SqlConnection.Dispose in turn closes the connection.
As you will see in Listing 2, we will also employ using for the TransactionScope object. TransactionScope’s Dispose method performs dozens of checks, rolling back the transaction if the complete flag is not set.
If complete is true, Dispose calls InternalDispose, whose purpose is to ultimately Commit the transaction if possible.
In essence, the outcome of exiting a using block is to commit a TransactionScope transaction if updates succeeded.