For the most part the GC will do the cleanup for you. This normally is fast enough for standard applications.
If you have particular resources that need immediate cleanup, call their Dispose method. If what must be cleaned up is a class you are creating implement IDisposable and put the cleanup code in Dispose. Then have the code that instantiates your class call the Dispose method. If Dispose is not being called, either by you or the GC, then the object is not being destroyed. This would point to a possible design problem. In particular, it may indicate you have created a situation where your instatiated class has an indefinite lifetime, possibly one as long as the application is running. (Can you spell "Memory leak".) If this is the case, start tracking through your code, focusing on where your class is instatiated and where it goes out of scope. Implement IDisposable in any class where your class is used as the type for a module level variable and in the containing classes Dispose method call your class's Dispose method. Check to see if this solvces your problem. If not, then repeat with the containing class, and its containing class, and so forth until you get to the top of the object chain. When you run out of objects to implement IDisposable, stop. Good luck and have fun. - R.B. Davidson On Feb 9, 9:55 pm, PromisedOyster <[email protected]> wrote: > Can I please clarify what is best practice with the destruction of > class member variables. > > Say I have a member variable that has a default value (as shown > below), then should we set this to null on the Dispose method (if > applicable) - say in a WinForm. Otherwise should we derive it from > IDisposable and set it to null in Dispose method (the hassle is > ensuring that the Dispose gets called)? Alternatively, put in the > finalize method. > > Up until now, we have typically left 'as is' with no cleanup as we > thought the GC would destory. However, it appears to be taking ages > to get destroyed > > class ClassX > { > > ClassY y = new ClassY(); > > } > > class ClassY > { > > ... > > > > }- Hide quoted text - > > - Show quoted text -
