Reputation: 225
Let's say I have this:
public static class FooKeeper
{
public static List<Foo> foos = new List<Foo>();
}
public class Foo
{
public Foo()
{
FooKeeper.foos.Add(this);
}
}
I would like to do so that when an object of type Foo gets garbage collected, then I would manually remove it from the list in the FooKeeper class. Of course that doesn't make sense, since Foo objects cannot be garbage collected because FooKeeper will always have a reference to them.
Is there any way to tell GC to ignore that reference that the list in FooKeeper has? or some other way around this?
Upvotes: 0
Views: 1026
Reputation: 33381
Use WeakReference to achieve what you want.
public static List<WeakReference<Foo>> foos = new List<WeakReference<Foo>>();
Upvotes: 4