Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Create strong reference between objects, without one referencing the other

Tags:

c#

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

like image 333
KoenJ Avatar asked Oct 26 '11 06:10

KoenJ


1 Answers

Have a look at the ConditionalWeakTable Class.

Enables compilers to dynamically attach object fields to managed objects.

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

ConditionalWeakTable<Foo, Bar> table

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.

like image 83
dtb Avatar answered Oct 22 '22 01:10

dtb