Eric Wise

Sponsors

The Lounge

Blogs I Read

Fun & Games

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Set foo = Nothing?

It's my understanding that because the .NET Garbage collector looks at the heap, and checks to see if any variables on the heap are in scope that setting an object to nothing at the end of a function in VB .NET really doesn't gain you anything yet I see code like this often:

Try

      'Do Stuff

Catch

Finally

      'Set a bunch of objects = Nothing

End Try

Is there a valid reason to do this in your methods that I'm missing?  Or is this just a habitual holdover from VB 6.0 programmers?


Posted 07-29-2004 10:48 AM by Eric Wise

[Advertisement]

Comments

Dave Truxall wrote re: Set foo = Nothing?
on 07-29-2004 7:45 AM
I have the same question. I keep seeing it in other developer's code, but like you I thought it was unnecessary. I thought the only objects you needed to address in the finally clause were ones that implmented IDisposable or interfaced with unmanaged resources.
Rob Teixeira wrote re: Set foo = Nothing?
on 07-29-2004 8:09 AM
It is habitual programming. There is no need to set a *local* variable to nothing, as the reference will be wiped off the stack when the function ends and unwinds the stackframe. Assuming the heap object data for that reference has no other references, the GC will take care of it later.

However, your Finally block *should* properly call Dispose or Close for objects containing unmanaged resources. Only a percentage of objects have a Dispose or Close method, so it's not something you have to do for everything, and certainly not for entirely-managed objects that you write.
Travis wrote re: Set foo = Nothing?
on 07-30-2004 4:21 AM
Also, for performance reasons, it sometimes can be better to release the managed resources as soon as possible. How much gain you get? I'm not sure.