Chaining Using Statements in C#

      No Comments on Chaining Using Statements in C#

I found this trick when doing a code review with my team at VML Kalamazoo.  Someone was presenting a queue processor they wrote and part of the their database interaction code included a clever convention.

I’ll admit, part of this uses a feature in C# that I try to avoid.  It’s perfectly legit to omit curly braces for the body of a control structure if it’s only one line long

            if (condition)
                throw new Exception("Something terrible happened!");

I find myself in the camp that you should always use curly braces. Usually my argument for that is that it makes it easier to modify in case the block in question needs to become more complicated in the future.

Meanwhile, throughout most any application you’ll be dealing with unmanaged resources (ex. database connections).  The best approach when dealing with these items is to leverage the IDisposable interface and the complementary using statement.  But in the most common case on a database interaction, you’re probably simultaneously dealing with multiple resources like a connection, transaction, command and/or reader.  For that type of situation, you can actually “chain” all of those using statements together.  Take for example a function I wrote that checks to see if a record exists based on a row count matching an ID.

        public bool EntityExists(Guid id)
        {
            using (DbConnection conn = GetConnection())
            using (DbTransaction trans = conn.BeginTransaction())
            using (DbCommand cmd = CreateEntityCountByIdCommand(conn, trans, id))
            {
                return ((int)cmd.ExecuteScalar()) > 0;
            }
        }

Part of what makes this possible is that I’m doing much of the prep of my unmanaged resources from within functions (GetConnection, CreateEntityCountByIdCommand).  I’m an advocate of breaking up code into smaller and smaller chunks.  For one, you can immediately use that block of code in multiple areas of your class/application.  And, perhaps more important, your code reads more like language and is self-commenting.

Another cool thing to point out is that it is perfectly fine to have a return statement within a using block.  The compiler knows to perform all the IDisposable.Dispose() functions before giving the result of your function back to the outer block.  All in all, I turned what could have been a function with a couple dozen lines to 4.

Leave a Reply