Disposing Object in VB.Net

How to dispose objects created in a Sub or functions like this:

Public sub MyXTree()
Dim mynode as treeview

Dim xString as string

'Do some thing with xtree
for mynode in Treeview.Node
xstring = mynode.text

Mynode=Nothing '? is this the right method of disposing
xString = Nothing '?is this the right method of disposing?
End Sub

'In VB6 by declaring nothing we can dispose off the object provided the object is not called immediately. Otherwise same reference of the object will be created with garbage value.
'I want to know how to dispose object declared inside a sub or function after the work is done.
'Friends if u know please Write to me.


  • Setting an Object to Nothing is one way of telling the system that it is no longer needed. (If it goes out of scope, it will automatically be marked up for destruction.) In either case, the object will be destroyed by the .Net Framework .

    Setting an object to Nothing in VB.Net doesn't have quite the same effect as doing this in VB6. In .Net the Nothing keyword tells the system that the object can be freed up (as opposed to VB Classic where it more or less instantly freed up the memory and resources).

    Note that in .Net the object is not actually released from memory until the Garbage Collector has kicked in.

    You probably are already aware that in the example you give:
    Dim mynode as treeview
    at this stage the mynode variable is Nothing. It has to be initialized with the New keyword before it actually represents an object. (Just thought I would mention it in passing)

    Anyway, see if this code helpts to clarify it:
    (I've assumed that you meant to create MyNode as a TreeNode, not a TreeView as you have posted (?).
    ' Declare a variable for a TreeNode
    Dim MyNode As TreeNode
    ShowState(MyNode) ' State?

    ' Instantiate it
    MyNode = New TreeNode
    ShowState(MyNode) ' State?

    ' Set it to Nothing
    MyNode = Nothing
    ShowState(MyNode) ' State?

    The above is normally all you need to do to dereference an object and wait for it to be garbage collected. If for some reason you have to be sure that it really has been completedly removed from memory, then you can force the Garbage Collection to collect immediately with:

    Note that forcing the GC to kick in too often is very inefficient and so should only be used with care.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion