Hey,
If I have an object, how can I set it to nothing?
I want to be able to check with is nothing.
Calling the dispose method doesn't set the object to nothing. I want the object to be in the same state as when I was declared.
Thanks,
Printable View
Hey,
If I have an object, how can I set it to nothing?
I want to be able to check with is nothing.
Calling the dispose method doesn't set the object to nothing. I want the object to be in the same state as when I was declared.
Thanks,
Depending on the object you can do a .Close that also calls the .Dispose method.
Also, actually setting the object equal to nothing works too. oApp = Nothing.
Finally you can call a garbage collection with GC.Collect().
This is how I personally handle connection objects
VB Code:
Private Sub QueryDB() [INDENT] Dim oConn as SqlConnection Try oConn = new SqlConnection("connection string") oConn.Open() ' execute query Catch ex as Exception Finally If Not (oConn is Nothing) Then With oConn If .State <> StateClosed Then .Close() End If End With oConn = Nothing End If End Try [/INDENT] End Sub
You don't set objects to Nothing. An object is something, not Nothing. You can set a variable to Nothing, so instead of referring to an object, which is something, it will refer to Nothing:Note that this does not affect the object though. If an object has a Dispose method then you should call it when you have finished with the object. Setting a variable to Nothing generally has no useful effect, although there are some cases where it does. If your variable will lose scope immediately or almost immediately anyway then it is pointless.VB Code:
myVar = Nothing
Yes, but you know we have this discussion allot but an Object can be set to Nothing. It just reinforces the Disposal of the object if it hasnt gone out of scope
:)
Also if you have a load o references all pointing to the same object then setting one of those references to nothing will not affect either the object or the other references.
You never actually dispose in that cleanup...Quote:
Originally Posted by Mr.No
VB Code:
Finally If Not (oConn is Nothing) Then With oConn If .State <> StateClosed Then .Close() End If .Dispose End With oConn = Nothing End If