views:

391

answers:

3

In C# code, I have three objects A, B and C. A and B each hold a reference to C. When A is destroyed I would like the reference from B to C to be deleted as well so that C can be destroyed by the Garbage Collector.

Is there a way to do this without deleting it manually from B? (The destructor in C is not called before the reference from B to C is deleted, so it is not effective here.)

+7  A: 

First off, define "remove". And then consider using WeakReference class.

Anton Gogolev
+10  A: 

It smells like a job for a WeakReference:

A weak reference allows the garbage collector to collect an object while still allowing an application to access the object. If you need the object, you can still obtain a strong reference to it and prevent it from being collected.

Sounds like you should refer from B to C via a WeakReference, instead of directly.

Vojislav Stojkovic
+5  A: 

Solution 1

Is B referenced from anywhere else in you application?

If B is only accessable through A, then B and C will be "removed" when A is "removed".

Solution 2

You should send a signal to B when A is "removed". If B is known to A you can signal B from A. I would use an IDisposable pattern for this

Solution 3

Instead of directly referencing C from B, you can use a WeakReference from B to get to C.

GvS
+1 for IDisposable
Daniel Schaffer
thank you, I will consider all three.
Fredriku73