4

Consider the following classes in C#:

class A
{
    public B b;
}

class B
{
    public A a;
}

Later:

{
    A a = new A();
    B b = new B();
    a.b = b;
    b.a = a;
}

The question: When execution falls out of this scope, will either instance be garbage collected, as there is still a reference to each of them, held by the other?

Matthew Kennedy
  • 616
  • 4
  • 19

2 Answers2

4

Yes, they both will. The GC walks the dependency tree and sees that neither of them are reachable by any other part of the program and will dispose of them properly.

Here is a good MSFT article: http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
1

Yes, they will be garbage collected. Circular References Cause Memory Leak?

Community
  • 1
  • 1
Bill Gregg
  • 7,067
  • 2
  • 22
  • 39