Removing items from lists and all references to them

c#, list, reference

Solution

Change your Node to include a list of the branches it is on:

public class Node
{
    // Has Some Data!

    public List<Branch> BranchesIn;
    public List<Branch> BranchesOut;  // assuming this is a directed graph

    public void Delete()
    {
      foreach (var branch in BranchesIn)
        branch.NodeB.BranchesOut.Remove(branch);

      foreach (var branch in BranchesOut)
        branch.NodeA.BranchesIn.Remove(branch);

      BranchesIn.Clear();
      BranchesOut.Clear();
     }
}

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

Now your Graph class doesn't need a List of Nodes or Branches, all it needs is a single Root Node. When you remove a Node you remove all the branches off it. Clearly you encapsulate all the methods to add and remove nodes and branches so external code can't break the structure.

If you aren't actually storing any data on the Branch (more typically called an Edge) you don't need it at all. Nodes can just maintain a list of the other nodes they link in from and out to.

Problem

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?

Original source