So, I have this project that creates multiple instances of a class, and list them.
At some point, the instanced class is not needed anymore. How can I flush it ?
So far, it doesn't happen, even when the class has nothing to do anymore (if it had been a single static class, the program would have shut down), it's still in my list, and its public variables are still available ...
You can have your instances raise an event (OnInactivated, say). The list class should add a handler for such events when the item is added to the list (subclass or encapsulate a list and override the Add method). When the event fires, the object will be removed from the list by the list. Assuming the object is not referenced in any other lists (which might also be listening), then the garbage collector is free to deal with the object.
In this way, the object does not need to keep track of all references to itself, and know how to inform the reference holder to release the reference.
Here's a runnable example: http://www.coderun.com/ide/?w=Hw83i0wAQkugUif5Oj2lmw