setting objects to nothing

quwiltw

Contributor
Joined
Sep 18, 2001
Messages
486
Location
Washington, D.C.
Anyone got any thoughts on setting their object references to nothing? I've found conflicting information on the subject: some say that the garbage collector is smart enough to clean up our mess and others say to use the old Set objXXX = Nothing like VB6. So far I've been safely assuming the former is correct, but just wondered if anyone has found different?
 
The short answer is yes, it's clever enough. As soon as the variable goes out of scope it is essentially set equal to nothing anyway, as it was in COM and VB6. The only possible advantage is that the GC *might* release it slightly sooner.
 
I've been wondering, when using GDI+ objects such as brushes
and pens, do you have to call the Dispose method of each one
when their use is finished to free up memory, or does the GC
dispose them automatically when they go out of scope?
 
GC will clean them up fine, but it's often preferable to .Dispose them yourself, and it's good practice. But it doesn't actually make much of a difference :)
 
Some objects you MUST call Dispose on yourself, to free memory. Things like DeviceContexts come to mind though I haven't used them in .NET. I know Graphics objects that you create must be disposed (not the ones passed in as an argument to a Paint event). I suspect that the Graphics object is creating a DeviceContext behind the scenes. If you don't call Dispose it doesn't get released til the Garbage Collector runs (and maybe not even then).

There are other things to be aware of when using Dispose, especially if you create your own object. Read through the help on it to get more info.

-n
 
Back
Top