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?
My personal way of using this might fit the bill:
private const string SQL_CONNECTION = "Your Connection String Here";
private void Test(string sqlCmd)
{
using (var cmd = new SqlCommand(sqlCmd, new SqlConnection(SQL_CONNECTION)))
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
// Close() is not really necessary.
// Dispose will Close the connection.
}
}
No, this is not two instances of the using clause in one line, but it is as compact as you are trying to get in your example.
What's more, you can make this even more compact and programmer friendly by turning your connection string into a Private Property:
private SqlConnection OpenConnection
{
get {
var con = new SqlConnection(SQL_CONNECTION);
con.Open();
return con;
}
}
Now, that first bit of code above in Test() could be shortened to the following:
private void Test2(string sqlCmd)
{
using (var cmd = new SqlCommand(sqlCmd, OpenConnection))
{
cmd.ExecuteNonQuery();
}
}
That makes coding very nice.