The TransactionScope expects a call to its Complete method as follows. Otherwise the transaction will not be committed.
using(TransactionScope scope = new TransactionScope())
{
/* Perform transactional work here */
scope.Complete();
}
Wouldn't an implementation that assumes success have been more appropriate? This would mean that less code would be required in the standard case (success).
In the case of an exception or a call to a method such as 'Rollback' (this method does not currently exist) the transaction could be rolled back.
using(TransactionScope scope = new TransactionScope())
{
/* Perform transactional work here */
if(problemOccurred)
{
scope.Rollback();
}
}
Note that the problemOccurred flag would only be required in cases where the problem did not result in an exception. In this case, the rollback would be performed automatically.
I am interested in gaining further insight into why this implementation was used.
Update: A couple of the answers so far argued that a try-catch block would be required if the implementation that I described were used. This is not the case. The transaction is automatically rolled back when an exception is not handled within the using block. This is the case in both the existing implementation and the one that I described. See 'Completing a transaction scope' section here for further details.
Update 2: I finally understand what was being explained in the answers. This is not a language construct that could have been interpreted any way that the language designers saw fit - it is an implementation of the IDisposable pattern. Without the call to Complete the code within the Dispose method would have no knowledge of whether it is being called as the result of the code within the using block being executed successfully or because an exception occurred. I was imagining something similar to the following where both transaction and rollback are keywords.
transaction
{
/* Perform transactional work here */
if(problemOccurred)
{
rollback;
}
}
This would of course present problems if transaction options need to be passed to the TransactionScope.