Is reusing a variable in VB6 a good idea?


Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong. Will it cause a memory leak.



dim mySQL as new sqlcommand(sSQL, cnInput)

// do a sql execute and read the data 

mySQL = new sqlcommand(sSQLdifferent, cnInput)

// do sql execute and read the data
catch ...


if mysql isnot nothing then
   mysql = nothing
end if

EDIT: put try catch in to avoid the comments about not using them

9/2/2011 6:04:36 PM

Accepted Answer

Just to extend what Longhorn213 said, here's the code for it:

Using mysql as SqlCommand = new SqlCommand(sSql, cnInput)
  ' do stuff'
End Using

Using mysql as SqlCommand = new SqlCommand(otherSql, cnInput)
  ' do other stuff'
End Using

(edit) Just as an FYI, using automatically wraps the block of code around a try/finally that calls the Dispose method on the variable it is created with. Thus, it's an easy way to ensure your resource is released.

9/3/2008 7:59:08 PM

One thing I never worked out - If I have a class implementing IDisposable, but I never actually dispose it myself, I just leave it hanging around for the GC, will the GC actually call Dispose for me?


Uh, to all those people saying "it's OK, don't worry about it, the GC will handle it..." the whole point of the Dispose pattern is to handle those resources the GC can't dispose of. So if an object has a Dispose method, you'd better call it when you're done with it!

In summary, Longhorn213 is correct, listen to him.


No, the garbage collector will find the old version of mySql and deallocate it in due course.

The garbage collector should pick up anything that's been dereferenced as long as it hasn't been moved into the Large Object Heap.


Be careful. If you have to do a lot of these in a loop it can be slow. It's much better to just update the .CommandText property of the same command, like this (also, you can clean up the syntax a little):

Using mysql as New SqlCommand(sSql, cnInput)
  ' do stuff'

    mySql.CommandText = otherSql

   'do other stuff'
End Using

Of course, that only works if the first command is no longer active. If you're still in the middle of going through a datareader then you better create a new command.


Whilst garbage collection will clean up after you eventually the dispose pattern is there to help the system release any resources associated with the object sooner, So you should call dispose once you are done with the object before re-assigning to it.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]