System.Transactions, interesting tidbit


Florin Lazar has an interesting post on using C# 3.0 to make writing transaction blocks a little ‘pithier’. In ‘A Simpler TransactionScope‘, he suggests using a delegate and a lambda expression to accomplish his goals.

transacted(()=>
{
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
      connection.Open();

      SqlCommand command1 = new SqlCommand(commandString1, connection);
      command1.ExecuteNonQuery();

      SqlCommand command2 = new SqlCommand(commandString2, connection);
      command2.ExecuteNonQuery();
   }
});

delegate void TransactedCodeDelegate();
void transacted(TransactedCodeDelegate txCode)
{
   using (TransactionScope ts = new TransactionScope())
   {
      txCode();
      ts.Complete();
   }
}

The thing that bothered me about this is, can’t I approach this using C# 2.0? And, yes, I can!

transacted(delegate()
{
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
      connection.Open();

      SqlCommand command1 = new SqlCommand(commandString1, connection);
      command1.ExecuteNonQuery();

      SqlCommand command2 = new SqlCommand(commandString2, connection);
      command2.ExecuteNonQuery();
   }
});

In case you are missing the change, Florin suggests using ()=> (4 characters) and I suggest using delegate() (10 characters). Otherwise, these are identical. They both use an anonymous delegate to get the job done.

I’m not suggesting that Florin’s method is flawed. I’m just suggesting that folks who still use VS 2005 in their day to day job can pick up this trick without an upgrade.