views:

46

answers:

2

Is there any way of associating an object instance (object A) with a second object (object B) in a generalised way, so that when B gets collected A becomes eligable for collection? The same behaviour that would happen if B had an instance variable pointing to A, but without explicitly changing the class definition of B, and being able to do this in a dynamic way?

The same sort of effect could be done by using the Component.Disposed event in a funky way, but I don't want to make B disposable

EDIT

I'm basically creating a cache of objects that are associated with a single 'root' object, and I don't want the cache to be static, as there can be lots of root objects using different caches, so lots of memory will be used up when a root object is no longer used but the cached objects are still around.

So, I want a collection of cached objects to be associated with each 'root' object, without changing the root object definition. Sort of like metadata of an extra object reference attached to each root object instance. That way, each collection will get collected when the root object is collected, and not hang around like they would if a static cache was used.

+1  A: 

Short answer: Probably not. Can you explain more of what you're trying to do? There's a chance WeakReference might be what you need.

Scott J
A: 
public class RelatedReference<A, B>
{
    private A a;
    private B b;

    public B Referent
    {
        get {return b;}
    }

    public RelatedReference(A a, B b)
    {
        this.a = a; 
        this.b = b;
    }
}

Then just use RelatedReference every where you would use B like so:

    var Bref = new RelatedReference<A, B>(new A(), new B());
    Bref.Referent.Foo();
Rodrick Chapman
Could you explain in more detail how this helps?
thecoop
If another object has a reference to B, B still won't be collected.
Scott J
Yes, you have to be careful not to set any other references to B. I also agree that the WeakReference class might be the way to go.
Rodrick Chapman
@thecoop - You're essentially accessing everything through a generic wrapper object. Once the wrapper object is collected, all of its references are collected. You do have to be careful not to assign the Referent property to any other variables though so this solution is a bit brittle... but it will work in general.
Rodrick Chapman