Transactions and Anonymous Methods

Oren raised a suggestion for a new C# feature (a new trend? :D) that will include a keyword that would work like using does with try/finally, only this keyword would include try/catch/finally, in a kind of transaction (commit/rollback) fashion.

I think there isn’t really a need for such a feature. One could simply do the following:

Utils.Control(delegate() {
    // code...
});

public static class Utils
{
    public static void Control(EmptyDelegate method)
    {
        try
        {
            method();
            Commit();
        }
        catch (Exception ex)
        {
            Rollback();
        }
        finally
        {
            Cleanup();
        }
    }
}

This could really simplify things, since the scope of the anonymous method is a sub-scope of the caller to Control.

Advertisements

8 thoughts on “Transactions and Anonymous Methods

  1. It all depends on what you want to do. Since I don’t know System.Transactions, I couldn’t answer your question directly.

    This is just a ‘proof-of-concept’ for a debate. You shouldn’t use this literally, but see this as a concept your can develop for your own needs.

  2. I’ve used this before, but i don’t consider the resulting code readable / maintainable in the long run.

    Utils.Control(delegate{
    Foo();
    if(fubar !=null )
    Bar();
    });

  3. You can see my comments at the original post. I think I’ll elaborate on this matter in my blog as I want to express my feelings about delegates and their pros & cons.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s