PersistenceOfVision
PersistenceOfVision

Reputation: 1295

Using statement with more than one system resource

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.

Upvotes: 10

Views: 6103

Answers (2)

bobbymcr
bobbymcr

Reputation: 24167

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.

Upvotes: 14

Andrew Hare
Andrew Hare

Reputation: 351556

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.

Upvotes: 0

Related Questions