Consider these two classes:
public class A { B b; public A(B b) { this.b = b; } } public class B { A a; public B() { this.a = new A(this); } }
If I have the classes created above, will objects of such classes be collected by the garbage collector (GC)?
Suppose I do this:
void f() { B b = new B(); }
In this method, I create an instance of B called B , and when the method returns, B goes out of scope and the GC should be able to collect it, but if it should collect it would have to first collect a , which is a member of B , and collect a , he needs to first collect B , which is a member of a . It becomes circular. So my question is: is such a circular reference a prevent collection of GC objects?
- If so, how can we avoid this problem? How can we make sure we donβt have a circular link in our class? Is there any tool (or compiler option) that helps us detect a circular reference?
- If not, where and why do we use the
WeakReference class? What is his purpose?
garbage-collection c # circular-reference
Nawaz Jan 12 2018-12-12T00: 00Z
source share