Dispose – Dispose – Dispose – even if it doesn’t do anything

I am always astounded how often I inherit code from smart developers who know what they are doing, but still do not take the time to close and destroy objects. As much fuss is made about memory management and such, this is still an area of coding where laziness abounds.

.Net memory management and garbage collection is intended to free up our need to manage memory at a micro level, but at the same time it is criticized for not freeing up memory fast enough and then blamed for application issues and server slowness. For best practices, never rely on inherent memory management. Where you can, close and DISPOSE!

Data objects inherit their object model from the control model, and thus by default they will have a dispose() method. I will readily admit that this method is not always actually implemented in the .NET framework. In other words, it does not always do anything. Some objects actually have no backend code for this method and your additional line of code had no effect whatsoever. In my opinion however, this does not mean you should not call the method. Since the method stubs are included, there is no reason not to believe that as updates to the framework are released that Microsoft will not take further steps to improve Memory Management and Garbage collection by implementing more cleanup in this method.

As a developer, it is up to you to manage your objects, from cradle to grave. I have made it a practice to write in all of my disposal lines of code right after I open or create a data object, then I back up and insert the usage code between the open and the close/dispose. By thinking of this as part of the object creation, you;ll rarely leave objects hanging out there.

Leave a Reply