I know that when an object has no references, the garbage collector frees the memory. But I have a doubt.
I have a class that is represented by a tree:
class MyNode
{
string Name;
List<MyNode> Descendants;
MyNode Parent;
}
When I create a node that has descendants, I have the reference to the node and also the son has a reference to the node in the Parent property. Also, the node has a reference to the descendant in the list of descendants.
So an example.
Node myNode = new Node();
Node myDescendant = new Node();
myNode.Descendants.Add(myDescendant);
myDescendant.Parent = myNode;
I can delete the reference to myNode
setting it to null
. However, the object is still referenced because myDescendant
references to it in the Parent
property. The myDescendant
object is not recollected because is referenced in the descendants list of the node object.
So it seems that there are a cycle that avoid the node recollection. Is this true? Perhaps I need to set to null
all the properties in the node and in the descendants and clear the list of descendants?
Thanks so much.