I know this question has already been asked, but my question is more general than the others I've seen.
When I was checking in my program my use of controls in Forms, and commands for DB(Commands, Readers, etc), the following question came to me:
If I have a Control, shouldn't I Dispose it after I use it?
That way I will make sure that my program is using only the resources that are needed, and if I must use a control that was already disposed then I'll just load it again.
Maybe there's a reason to not dispose everything always, but that's why I'm asking this question.
Thanks for any answer and I hope I made myself clear.
Non-visual components you create (commands, readers, I/O components, basically anything that implements IDisposable) should be disposed after you're done with them.
For visual controls, the Form's Dispose function should dispose of all controls in it's Controls collection automatically, so you would only need to worry about controls that you remove from the form's Controls for some reason.
Unless you're experiencing serious memory problems it's probably a micro-optimization to try and dispose of form controls manually.
Yes, if no concrete reason speaks against it, you probably should dispose everything. Controls are automatically disposed of when in a Form and the Form is disposed.
Not disposing of UI resources is not very harmful. It is just a little more memory are system resource usage than necessary. This is in most cases not a functional problem.
This is in contrast to database connections and files, of course! Disposing of them is critical.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With