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?
There's no built-in C# language feature to facilate that (you can't really track assignments). You'll have to keep track of all references somewhere and update it as soon as you're assigning a new reference to it. A very general idea is to provide a Removed
event in the Node
itself and raise the event when the object is supposed to be abandoned. Every time you want to hold on a new reference to the Node
, you'd subscribe to the event with a matching delegate that nulls out the reference to that object.
Of course, if you're doing this with a set of previously known types that reference the node in a specific way, there may be easier and more efficient ways to accomplish the task.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With