0

I have three objects A, B and C. C is the child of both A and B. C has reference to A and B. A and B has reference to C. I understand that when the reference to C from both A and B gets deleted, C becomes garbage and will be collected by GC.

  1. Is my understanding correct?
  2. Should I set the Reference to A and B in C to NULL?
  3. If Yes, What is the benefit?
  public class A { public C Cr { get; set; } } public class B { public C Cr { get; set; } } public class C { public A Ar { get; set; } public B Br { get; set; } } class Program { static void Main(string[] args) { var oa = new A(); var ob = new B(); var oc = new C(); oc.Ar = oa; oc.Br = ob; oa.Cr = oc; ob.Cr = oc; // Some operation oa.Cr = null; ob.Cr = null; //is the following code required? // if yes, what is the benefit? oc.Ar = null; oc.Br = null; }  

Thanks

Ram

2
  • 6
    Please show code instead of describing things in relatively woolly terms. The concept of one object being the "child" of another isn't well-defined... Commented Apr 13, 2011 at 10:00
  • This makes no sense. By "child of" do you mean inherits? If so, then you can't inherit from more than one class in C#. And if C inherits from B, then how in the hell does B inherit from C? Does not compute. Commented Apr 13, 2011 at 10:02

1 Answer 1

7

If there are no live references to C, then it becomes eligible for garbage collection. That doesn't mean it will be garbage collected straight away.

There's no need for you to set references to null within an object if that object is about to become eligible for garbage collection.

Note that if there are no "root" references to A, B or C, they will all be eligible for garbage collection, even if they continue to have references to each other.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.