(FYI: This question is half thoretical. It is not something which I am definatly planning on doing.)
I would like to be able to keep a reference to all the objects that I create. Maybe like this:
class Foo
{
private static List<Foo> AllMyFoos = new List<Foo>();
public Foo()
{
AllMyFoos.Add(this);
}
}
The trouble with this is that now none of my Foos can ever drop out of focus and be garbage collected. Is there any way of keeping a referance without getting in the way of the garbage collector?
Ideally I just of a list of Foos that are still being used, not all Foos which have ever been used.
Use WeakReference – it does exactly what it is supposed to. Be careful while working with it – you have to check if the reference is still valid every time you dereference it.
Tutorial.
Warning: Just because the object hasn’t yet been garbage collected doesn’t mean someone hasn’t called
Disposeon it, or in some other way put it into a state that it is not prepared to be used again.