C# - Removing items from lists and all references to them.

Posted by LiamV on Stack Overflow See other posts from Stack Overflow or by LiamV
Published on 2010-04-27T20:16:24Z Indexed on 2010/04/27 20:23 UTC
Read the original article Hit count: 332

Filed under:
|
|

Hi there, I'm facing a situation where I have dependent objects and I would like to be able to remove an object and all references to it.

Say I have an object structure like the code below, with a Branch type which references two Nodes.

public class Node
{
    // Has Some Data!
}

public class Branch
{
    // Contains references to Nodes
    public Node NodeA
    public Node NodeB
}

public class Graph
{
    public List<Node> Nodes;
    public List<Branch> Branches;
}

If I remove a Node from the Nodes list in the Graph class, it is still possible that one or more Branch objects still contains a reference to the removed Node, thus retaining it in memory, whereas really what I would quite like would be to set any references to the removed Node to null and let the garbage collection kick in.

Other than enumerating through each Branch and checking each Node reference sequentially, are there any smart ideas on how I remove references to the Node in each Branch instance AND indeed any other class which reference the removed Node?

Much appreciated, Liam

© Stack Overflow or respective owner

Related posts about c#

Related posts about list