Friday, May 07, 2004
Don't null objects

In a design session earlier this week, two of us were working on our transaction handler.  One of the things that came up was how to implement IDisposable, since we wanted to make sure we did some housecleaning when the unexpected happens. 

We all know that we're in a managed environment now, and sometimes it becomes unclear to the developer what, and when to clean.  One thing we visited is setting objects to null/nothing.  I was pretty surprised to read that this can extend the life of your objects, but after thinking about it, it makes total sense.

The GC collects based on when the object was last used, and the CLR sees setting an object to null/nothing as a use, therefore settings to null/nothing has the possibility of extending your objects life. 

It is important to understand the distinction between disposing an object, and setting it to nothing.  The IDisposable pattern notes that in Dispose() we should free unmanaged resources, which is still very important.

Moral of the story, in most situations its appropriate to just let your objects falls out of scope, unless you are utilizing managed resources, in which you should implement IDisposable.  Not new information for anyone, but a friendly reminder since it was on my mind.