Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an advantage to USING vs. declaring a context variable?

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?

like image 635
gfrizzle Avatar asked Dec 02 '22 07:12

gfrizzle


2 Answers

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.

like image 172
Jon Skeet Avatar answered Dec 18 '22 21:12

Jon Skeet


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
like image 28
Meta-Knight Avatar answered Dec 18 '22 23:12

Meta-Knight