Since C# uses Garbage Collection. When is it necessary to use .Dispose to free the memory?
I realize there are a few situations so I’ll try to list the ones I can think of.
- If I close a Form that contains GUI type object, are those objects dereferenced and therefore will be collected?
- If I create a local object using new should I .Dispose of it before the method exits or just let the GC take care of it? What is good practice in this case?
- Are there any times in which forcing a GC is understandable?
- Are events collected by the GC when it’s object is collected?
In theory, if you have properly defined componentry, it should never be required to call Dispose() on your objects, as the finalizer should eventually take care of it.
That being said, any time you’re using an object that implements IDisposable, it’s a good practice to call Dispose() on the object as soon as you are through working with it.
For some of your specific points:
1) If you know you’re “done” with the Form, you can call Dispose() on it. This will force a cleanup at that point in time of the unmanaged resources associated with the form.
2) In this case: if your object is just used in that method, use “using” instead:
3) There are rare reasons to do this, but in general, no.
4) Events are a delegate – the memory associated with the delegate will be collected after the delegate itself becomes unrooted, which typically happens when the objects in question are unrooted.