开发者

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

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(itemNum开发者_如何学Pythonber,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


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜