Reputation: 7433
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?
Upvotes: 2
Views: 1796
Reputation: 273169
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.
Upvotes: 6
Reputation: 35584
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.
Upvotes: 0
Reputation: 160852
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.
Upvotes: 2