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.
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.