Basically, the best approach is collecting all of the instances in some container. Wait a minute, not so fast. There is a possibility that your thinking is to abuse the garbage-collected architecture. But maybe not. Let's sort it out.
You cannot just "remove instance", as there is no such thing in managed application. You only need to remove the referenced to the instances, and they are, again, are stored in some container. So, in the simplest case, you simply need to clear the container.
I hope you already understand this, but it need some clarification. Any object on heap will be destructed and removed from memory by the Garbage Collector (GC) if your object lost its
reachability
. Reachability is not a simple concept at all. For example, if three objects are referencing each other in cycle (A -> B -> C -> A), but there no more references to either of them, they will be garbage-collected anyway.
I can imagine that your picture is more complex. There are many different containers, nesting containers, each containing objects of different types, polymorphous or not. Usually, you should recursively traverse all your containers and clear them. This is the best way.
Let's imaging that this is difficult for you, by whatever reason. Then you could collect all the child-parent relationship to be cleared in some separate container. The storing is not trivial; you will need to store some data and references needed to remove an object from its parent container. Maybe, it should be just the collection of containers. It depends on your design which I don't know. My thing is to give you the right idea.
The problem here is this: this extra collection itself will hold objects and thus will keep them from collection. There are two ways to work around this problem. 1) You will need to clean this extra collection itself when the work is done; 2) you can hold not "real" references, but "weak references", which can be used for referencing by will allow garbage collection.
The problem of weak referencing is resolved using the class
System.WeakReference
, please see
http://msdn.microsoft.com/en-us/library/system.weakreference.aspx[
^].
I would also recommend to read the interesting articles by CodeProject author
Paulo Zemec:
Creating a Weak List[
^],
WeakReferences, GCHandles, and WeakArrays[
^],
Creating a weak event[
^].
—SA