CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Eric Wise

Business & .NET

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?



Comments

Rob Teixeira said:

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.
# July 29, 2004 8:09 AM

Travis said:

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.
# July 30, 2004 4:21 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!