Using various types in a 'using' statement (C#)

Andrei Rînea picture Andrei Rînea · Jun 8, 2009 · Viewed 9.2k times · Source

Since the C# using statement is just a syntactic sugar for try/finally{dispose}, why does it accept multiple objects only if they are of the same type?

I don't get it since all they need to be is IDisposable. If all of them implement IDisposable it should be fine, but it isn't.

Specifically I am used to writing

using (var cmd = new SqlCommand())
{
    using (cmd.Connection)
    {
        // Code
    }
}

which I compact into:

using (var cmd = new SqlCommand())
using (cmd.Connection)
{
    // Code
}

And I would like to compact furthermore into:

using(var cmd = new SqlCommand(), var con = cmd.Connection)
{
    // Code
}

but I can't. I could probably, some would say, write:

using((var cmd = new SqlCommand()).Connection)
{
    // Code
}

since all I need to dispose is the connection and not the command but that's besides the point.

Answer

Joseph picture Joseph · Jun 8, 2009

You can do this though:

using (IDisposable cmd = new SqlCommand(), con = (cmd as SqlCommand).Connection)
{
   var command = (cmd as SqlCommand);
   var connection = (con as SqlConnection);
   //code
}

Perhaps that would be satisfactory to you.