c# - Removing items from lists and all references to them -


i'm facing situation have dependent objects , able remove object , references it.

say have object structure code below, branch type references 2 nodes.

public class node {     // has data! }  public class branch {     // contains references nodes     public node nodea     public node nodeb }  public class graph {     public list<node> nodes;     public list<branch> branches; } 

if remove node nodes list in graph class, still possible 1 or more branch objects still contains reference removed node, retaining in memory, whereas quite set references removed node null , let garbage collection kick in.

other enumerating through each branch , checking each node reference sequentially, there smart ideas on how remove references node in each branch instance , indeed other class reference removed node?

change node include list of branches on:

public class node {     // has data!      public list<branch> branchesin;     public list<branch> branchesout;  // assuming 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 nodes     public node nodea     public node nodeb } 

now graph class doesn't need list of nodes or branches, needs single root node. when remove node remove branches off it. encapsulate methods add , remove nodes , branches external code can't break structure.

if aren't storing data on branch (more typically called edge) don't need @ all. nodes can maintain list of other nodes link in , out to.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -