There are times when it could make sense for a class which implements IDisposable
to have a cloning method, in which case whatever code invokes the cloning method the object would be responsible for ensuring that Dispose
will get called the new copy (either by calling Dispose
itself, or handing off the responsibility to some other code). There are also occasions when it makes sense to have a a container class with a Dispose
method that calls Dispose
on each member stored therein, though in most such situations the purpose of the container class would center around such disposal and there would be no reason for it to support any kind of cloning.
Unless the Node
class will be exposed to the outside world, I don't see much purpose for having it implement IDisposable
. Even if the class which holds the linked list is a disposal aggregator (something which accepts objects whose useful lifetime will be shorter than its own and then cleans them up when its own Dispose
method is called) and every node but the last will not only hold something that requires cleanup, but will also know of another node. Having a node call Dispose
on the next node would result in unnecessary recursion, causing a crash if there are too many nodes. An alternative would be to have the Node
class implement a Node DisposeAndReturnNext()
method which would cause the Node
to dispose of all resources it knows about and then return a reference to the next node. A caller could then use something like:
while(nodeToDispose != null)
nodeToDispose = nodeToDispose.DisposeAndReturnNext();
Here it would be clear that the DisposeAndReturnNext
method would not be expected to dispose the next node (and its descendants), even though it would know that they need disposal. While it would be possible for Node
to define a Dispose
method which includes a loop like the above, having the first list item's disposal handled a public Dispose
method and having every other item's disposal handled by a loop like the above seems rather icky. Better to have one loop, in the enclosing class, which handles disposal for everyone.