C# using statement, redux

Last week, I wrote about the things I had not known about the C# using statement:

Multiple objects can be used in with a using statement, but they must be declared inside the using statement, like this:

using (Font font3 = new Font("Arial", 10.0f), 
           font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

I’m beginning to wonder where it was I learned the using statement from, given that I really didn’t know this is supported. Granted, I learned my C# basics when the language was version 1.0, and while the older reference does have an example of this usage, it’s not as clear as the current version. Still, lacking this knowledge meant that I’ve (ab)used braceless blocks to achieve the same effect:

using (Font font3 = new Font("Arial", 10.0f))
using (Font font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}

I wasn’t actually as far off as I thought – what the documentation doesn’t clearly spell out is that the syntax for the variable declaration inside the using statement must match a normal variable declaration. And there’s no way to do this:

string foo = “bar”, int baz = 42;

Because C# only allows you to initialize variables of one type in one declaration, and the same limitation applies to the using statement. The compiler knows this, the documentation wasn’t so clear about it. I’ve rarely declared two variables of the same type like in my example – instead, it’s been more like this:

using (DbConnection connection = OpenConnection())
using (IDataReader reader = connection.ExecuteReader(“…”))
{
    // ...
}

in which case the neater syntax doesn’t actually work at all. So I’m still stuck with my syntax abuse, unless I want to nest blocks. And this sort of seems to communicate my intent: I’m trying to say, the usages of these two things are linked in scope. Were I to do something to the connection before running the statement, I’d of course indent them differently.

I’m still waiting for a better idea.

Leave a Reply

Your email address will not be published. Required fields are marked *