Search code examples
c#dispose

Why not Dispose always?


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.


Solution

  • 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.