These two snippets do the same thing - is there one that's better than the other, or is it just a matter of preference?
Using context As MyDatabaseDataContext = New MyDatabaseDataContext()
Dim test = context.Employees.Count
End Using
vs.
Dim context As MyDatabaseDataContext = New MyDatabaseDataContext()
Dim test = context.Employees.Count
I realize these are oversimplified examples - what are the scenarios where one one method would work better than the other?
The first calls Dispose
at the end of the Using
statement - that's the point of the Using
statement. It's equivalent to Try/Finally, so the resource is disposed even if an exception is thrown.
Tony the Pony's answer is exact, the point of Using is to dispose unmanaged resources once you're done with the object. The equivalent code to:
Using context As New MyDatabaseDataContext()
Dim test = context.Employees.Count
End Using
would be:
Dim context As New MyDatabaseDataContext()
Try
Dim test = context.Employees.Count
Finally
If context IsNot Nothing
context.Dispose()
End If
End If
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With