I have seen some code like this (not on consecutive lines, but in the same function scope):
Dim con1 As SqlConnection
con1 = New SqlConnection
'More code here
con1 = New SqlConnection
con1 = Nothing
I believe this is just a bug, but I wanted to check that there is not a form of shadowing going on here that I am unaware of. What happens to the first con1 variable? I assume it is inaccessible as there is no reference to the object.
What’s Happening Here
con1points to two different objects during the lifetime of that function.The first object, created by the first
is no longer referenced after the second
is executed.
Is this a memory leak?
No. The object that is no longer referenced will eventually be disposed of, then the GC decides to do so. However it is a resource leak. Every time you fail to close a SQL Connection (assuming it was opened and not just allocated), you leave a resource unavailable for reuse. The GC will trigger when memory is low, so you will certainly regain the unreferenced object’s memory at the latest when the system is low on memory (you will also regain the DB connection at that point). However, low resources will not trigger GC. You could run completely out of DB connections before the GC ever decides to kick in and release the SqlConnection objects (including the DB connections they were hoarding).
Fixing the Code
Since SqlConnection must be closed to release the connection, the first object will hang around until the GC decides to dispose of it. That is a bad thing, as SQL connections are a resource that should only be held as long as necessary.
Calling Close() the first connection before assigning the new SqlConnection object would improve the situation (also, call Close() on the second instance before leaving variable scope).
However, if you get an Exception somewhere in the code, without proper exception handling, you would still be left with undisposed objects until the GC kicks in. Always, always put exception handling around anything that manages a resource such as this.
The very best way to put exception handling in place for this scenario is with the Using keyword. I have never written a line of VB.Net until now, but here’s my attempt at a correct version of your code: