Suppose I have 2 classes, Foo and Bar.
Foo does not have (and cannot have) a relation to Bar.
However, I want a bar instance to stay alive, as long as it’s foo instance stays alive.
Is there any way of doing so, without foo actually referencing bar?
Thanks,
Koen
Have a look at the ConditionalWeakTable Class.
It’s essentially a dictionary where both the key and the value are a WeakReference, and the value is kept alive as long as the key is alive.
For example, you can define a
and add a Foo/Bar pair. The Bar instance is kept alive as long as a reference to the Foo instance exists. You can find the Bar instance for the Foo instance by looking at the table.