Home All Groups Group Topic Archive Search About

'Set Object = Nothing'... do you still do this in VB.net????

Author
21 Oct 2007 5:11 AM
Alan Mailer
I'm relatively new to VB.net.  Is it good practice to 'destroy'
created objects... or does VB.net take care of this for you in its
'garbage' collection.

For example, in VB6 we used to have to do a lot of the following:

Set myObject = Nothing

....after we were finished using myObject.  Is this still good practice
in VB.net?

Thanks in advance.

Author
15 Nov 2007 12:52 PM
Parikshit Sehgal
On Oct 21, 10:11 am, Alan Mailer <clarityas***@earthlink.net> wrote:
> I'm relatively new to VB.net.  Is it good practice to 'destroy'
> created objects... or does VB.net take care of this for you in its
> 'garbage' collection.
>
> For example, in VB6 we used to have to do a lot of the following:
>
> Set myObject = Nothing
>
> ...after we were finished using myObject.  Is this still good practice
> in VB.net?
>
> Thanks in advance.

Alan,

You will find lot of discussion on this.... But as per my exp. there
is no use to setting object  = Nothing in VB.NET
The only advantage (May be) is after you set the object = Nothing its
reference count will be reseted to 0 which makes this object as best
candidate to be collected by GC...

So while working with VB.NET there is no use to setting object =
nothing...But keep in mind.. if object is expensive then its better to
dispose the object.

Setting object  = Nothing doesnot gurantee that it will be collected
by GC sooon

Pariksh*t
Author
15 Nov 2007 2:02 PM
Jon Skeet [C# MVP]
On Nov 15, 12:52 pm, Pariksh*t Sehgal <ppseh***@gmail.com> wrote:

<snip>

> The only advantage (May be) is after you set the object = Nothing its
> reference count will be reseted to 0 which makes this object as best
> candidate to be collected by GC...

No - because objects *aren't reference counted*.

The only use is if you're within a loop or some other construct where
the JIT can't tell that you're not going to use the object again. For
instance (C# code, same applies in VB):

// Large object only needed in the first iteration of the loop
SomeObject foo = new SomeObject();
bool firstTime = true;

// Potentially long running loop
while (ReadData())
{
    if (firstTime)
    {
        foo.DoSomething();
        firstTime = false;
        foo = null;
    }
}

Jon

AddThis Social Bookmark Button