views:

127

answers:

6

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?

+10  A: 

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.

Jon Skeet
+1  A: 

The first one calls dispose at the end of the Using block. So yes there is an advantage there.

With LINQ2SQL DataContext's you have to be careful with deferred execution. You wouldn't want to put a deferred query in the Using block and after the Using block enumerate the results. You'll get an exception about the context being disposed.

You also have to be careful when using the Using block with WCF Service Clients. You can encounter problems with exception propagation.

Jason Punyon
+1  A: 

when you use using - the object is destroyed in the end of the scope of using, and not later. if the object has special resources to dispose - it will release them earlier - so when you use a db connection -it will be smart using "using" for example.

Dani
The object won't be destroyed. There is just a call to `Dispose()` which should cause the object to release any references to unmanaged resources. But the object still lives on afterwards. It might just be unusable, though.
Joey
It will not be usable.
Dani
@Dani: That's up to the type to decide. For example, you can still get the data out of a MemoryStream after it's been disposed, by calling ToArray.
Jon Skeet
Wasn't aware of this, thanks for the info.
Dani
A: 

Using guaranties that Dispose method will be called on context at the end of the block, even if exception was thrown.

It is important when working with disposable resources like files, db connections, etc.

Alex Reitbort
+2  A: 

The two snippets do NOT do the same thing. The first will dispose your data context at the end of the using block, even if an exception is thrown. The latter snippet will not dispose it, which potentially leaves an extra database connection hanging around.

Joel Coehoorn
+2  A: 

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
Meta-Knight