I wouldn't initialize the 'tr' variable inside the try block, because
that would cause the code in the finally block to call Dispose()
on it, no matter what. That's not exactly what you want.
As far as equating try/finally to what using() does, this would
be closer:
Transaction tr = myDb.TransactionManager.StartTransaction()
try
{
// use 'tr' here
}
finally
{
if( tr != null )
tr.Dispose();
}
If you want to test to see if the tr variable was correctly
initialized, you do something like this:
Transaction tr = myDb.TransactionManager.StartTransaction()
if( tr == null )
throw new InvalidOperationException("No transaction!");
try
{
// use 'tr' here
}
finally
{
if( tr != null )
tr.Dispose();
}
The odds that StartTransaction() will fail to return a valid
Transaction is slim-to-none, but if it ever did happen, your
code should not attempt to deal with it, because it means
something is wrong at the API level, rather than in your
own code.
Transaction tr = null;
try {
tr = db.TransactionManager.StartTransaction();
// more mojo here
} finally {
tr.Dispose();
}
using (Transaction tr = db.TransactionManager.StartTransaction();
{
// more mojo here
}
Okay, using sure gives cleaner code, but is there any way to capture an error thrown when the initialization of TR fails?