VB.NET difference between using multiple USING statement and using only one

1k views Asked by At

Which one is best approach out of the following? Or Both has same effect ?

Dim carrierName As String
Dim someotherName As String
Dim anotherOne As String

Using oDa As New MyCompany.DataAccess.MyModule
     carrierName = oDa.GetCarrierName(itemNumber)
End Using

Using oDa As New MyCompany.DataAccess.MyModule
     someotherName = oDa.GetSomeOtherName(itemNumber,1)
End Using

Using oDa As New MyCompany.DataAccess.MyModule
     anotherOne = oDa.GetAnotherName("somevalue")
End Using

OR

Using oDa As New MyCompany.DataAccess.MyModule
     carrierName = oDa.GetCarrierName(itemNumber)   
     someotherName = oDa.GetSomeOtherName(itemNumber,1)   
     anotherOne = oDa.GetAnotherName("somevalue")
End Using
4

There are 4 answers

3
Jon Skeet On

Well, one version will create three MyModule instances, the other will only create one. We can't tell what the difference is without knowing more about MyModule.

The second approach looks cleaner to me, but without knowing the semantic differences, it's hard to say that it's definitely better.

2
Tundey On

In the first, you are creating and disposing of 3 instances of MyModule while in the second you are only creating and disposing 1 instance. So the second approach is better. It's cleaner and more straightforward too.

0
Eilistraee On

The two approachs are fondamentally different, but the end result depend on your MyModule implementation.

The second one seems better, as it creates and manages only one MyModule object, especially if MyModule is costly to create and to dispose.

The first one can be necessary if your MyModule doesn't allow multiple requests with the same instance. But if it's the cas. hem... it would look like a bug to me.

1
Lukáš Novotný On

The latter is better in most cases. Using is just shortcut for

var oDa = new MyCompany.DataAccess.MyModule();
try {
    carrierName = oDa.GetCarrierName(itemNumber)   
    someotherName = oDa.GetSomeOtherName(itemNumber,1)   
    anotherOne = oDa.GetAnotherName("somevalue")
}
finally {
    oDa.Dispose();
}

First method could be used when every method allocates huge amount of memory that will need to be cleaned right away, but I don't think it is your case.

btw: you seem to have mistaken c# with visual basic