10

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.

2
  • Aren't those blocks just identical for the VB compiler? Commented Sep 3, 2009 at 15:37
  • Yes the blocks are the same to the compiler but very easily could cause confusion for someone not familiar with Using Commented Sep 3, 2009 at 18:03

2 Answers 2

14

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.

2
  • 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. Commented Sep 3, 2009 at 18:08
  • actually the vb version with line continuations is much more readable than the c# version! at least we are not seeing bunch of usings
    – Unicornist
    Commented Jul 11, 2014 at 18:11
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.