Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 942
PersistenceOfVision Avatar asked Sep 03 '09 15:09

PersistenceOfVision


1 Answers

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.

like image 74
bobbymcr Avatar answered Sep 30 '22 18:09

bobbymcr