Is it necessary to dispose of custom objects, even if they only contain managed objects? For example, I have a custom class that contains some List objects, as well as some string and xmldocument types. Should I create my own Dispose method (while NOT inheriting from IDisposable) and just clear those out to make sure they are empty? If I should, should I also inherit from IDisposable?
-
"Necessary" is a strong word. If they are big and unwieldy, or can take up significant, limited resources, it's a good idea to implement IDisposable to aid in freeing those resources. – Jeremy Holovacs Apr 20 '12 at 16:02
-
The FAQ answer goes in great detail on overall usage of IDisposabe and worth reading [Proper use of the IDisposable interface](http://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface). – Alexei Levenkov Apr 20 '12 at 16:06
-
@JeremyHolovacs - "big" is not relevant here, it's not about memory. Only about (managed) resources. – H H Apr 20 '12 at 16:19
-
@HenkHolterman, this is true (except it's about *un*managed resources); I stand corrected. – Jeremy Holovacs Apr 20 '12 at 16:26
-
@JeremyHolovacs - unmanaged should be wrapped in SafeHandle and then it's managed. – H H Apr 20 '12 at 16:30
3 Answers
Only when one or more of those managed objects inherits from IDisposable.
If you have IDisposable objects (aka managed resources) then implement IDisposable but do not add a destructor/finalizer.

- 263,252
- 30
- 330
- 514
-
-
@HenkHolterman the destructor/finalizer, is that the ~[MyCustomClassName] method? – ganders Apr 20 '12 at 17:37
As a rule of thumb you should implement IDisposable
if any of the managed object instances you reference implement IDisposable
. You can then dispose those in your Dispose
implementation.

- 158,293
- 28
- 286
- 335
You see, setting the references to null
at the end of your object's lifetime won't change anything for the garbage collector. If the only remaining references to the contained objects are from your custom object, then the garbage collector treats them as eligible for garbage collection anyway (because it looks only for references from living objects). If there are references from elsewhere, the contained objects won't be collected, no matter if you clean up your references.
Another story is, of course, when some of your contained objects requires explicit disposal, that is, implements IDisposable
, or requires to be closed at the end of lifetime (although the correct way would be anyway to implement IDisposable
), etc. This way you perhaps need to implement IDisposable
yourself, and dispose of the contained objects in your Dispose
.
Of course, you need to implement IDisposable
in a special way when you refer to unmanaged objects, but this is another story.

- 35,022
- 6
- 77
- 199