views:

180

answers:

2

I have used the "using" statement in both C# and VB. I agree with all the critics regarding nesting using statements (C# seems well done, VB not so much)

So with that in mind I was interested in improving my VB using statements by "using" more than one system resource within the same block:

Example:

Using objBitmap as New Bitmap(100,100)
    Using objGraphics as Graphics = Graphics.From(objBitmap)
    End Using
End Using

Could be Written like this:

Using objBitmap as New Bitmap(100,100), objGraphics as Gaphics = Graphics.FromImage(objbitmap)
End Using

So my question is what is the better method?

My gut tells me that if the resources are related/dependent then using more than one resource in a using statement is logical.

I have searched so and google for discussions/opinions on this with no luck so I am looking to our experts here to help me sift this question out. Thanks!

+1  A: 

They are both the same, you should choose the one that you find to be the most readable as they are identical at the IL level.

I personally like the way that C# handles this by allowing this syntax:

using (Foo foo = new Foo())
using (Bar bar = new Bar())
{
    // ....
}

However I find the VB.NET equivalent of this form (your second example) to be less readable than the nested Using statements from your first example. But this is just my opinion. Choose the style that best suits the readability of the code in question as that is the most important thing considering that the output is identical.

Andrew Hare
+1  A: 

My primary language is C#, and there most people prefer "stacked" usings when you have many of them in the same scope:

using (X)
using (Y)
using (Z)
{
    // ...
}

The problem with the single using statement that VB.NET has is that it seems cluttered and it would be likely to fall of the edge of the screen. So at least from that perspective, multiple usings look better in VB.NET.

Maybe if you combine the second syntax with line continuations, it would look better:

Using objBitmap as New Bitmap(100,100), _
objGraphics as Graphics = Graphics.FromImage(objbitmap)
    ' ...
End Using

That gets you closer to what I would consider better readability.

bobbymcr
I am accepting your answer due to the fact that you included the line continuation example. I was aware of it as an option to improve readability but using continuation really starts to make it look like everyone's preferred C# structure.
PersistenceOfVision