If I 'New' a class inside of a user control, do I need to explicitly delete it? I'm asking because I'm not seeing an easy way of determining when the user control itself is being deleted.
I have a form on which I drop a user control. The user controls instantiates another class object. I added code in the destructor of the user control to delete the class object, but it seems the destructor does not fire. There's also no closed or closing event on the user control.
I could subscribe to the user control's parent form closed event and delete the objects there, but I would think there's a better way.
Any suggestions welcome!
Thanks,
Jim
You might find this thread useful:
http://communities.progress.com/pcom/thread/17371
The short answer is: No. You don't have to explicitly delete stuff. You can if you want to.
If you don't explicitly delete it, the garbage collector will call the destructor eventually when it gets around to removing the object from memory. When that actually happens is based on a bunch of different factors, but it is always after the last reference to it is removed.
Generally, you shouldn't rely on destructors since they are unpredictable unless you care to put delete object statements everywhere.
Thanks Matthew. Good information.
My earlier 10.2 coding had 'delete objects' in the destructors of forms but I've been moving most of them to a closed or closing event. These methods don't exist for the user controls which is why I asked the question. I had heard that we now had garbage collection on items we create, but I still feel better deleting them myself when I can.
As Matt has written, you can delete, but you don't have to.
I believe deleting is still a good idea. It makes the intended life-time of an object so much clearer to humans (developers debugging code) and the machine.
Regarding the FormClosed event: I wouldn't use that on a general base to delete child objects. There may always be Forms a User closes but you migth still need to call into internal methods that depend on objects in a Form (like a Query or a BindingSource).
Or in another scenario the user might want to re-display a closed (= hidden) Form.