0

I am writing a Graph library in C#.

Here is my Graph.cs :

public class Graph : IGraph
{
    public HashSet<INode> Nodes { get; set; }

    public HashSet<IEdge> Edges { get; set; }
}
  • Rule 1 : When a Node is deleted, I want to all edges that deleted node was part of them , become deleted from HashSet of IEdge.
  • Rule 2 : When an Edge is added, I want to both Node instances in Edge instanse add to HashSet of INode.

What can I do for gaining this behavior?

Now, the library user simply use :

g.Edges.Add(new Edge(n5, n6));

that n5 and n6 are Node instanses but there is no n5 and n6 in g.Nodes HashSet.

I was wondering if there is a way that I could call a method like this when an Edge instanse is added to HashSet in the Setter of Edges property :

void UpdateNodes(IEdge edge)
{
     Nodes.Add(edge.A_Node);
     Nodes.Add(edge.Another_Node);
}
Parsa
  • 7,995
  • 2
  • 27
  • 37
  • 1
    You can wrap/extend the `HashSet` by implementing the `INotifyCollectionChanged` interface. Then, subscribe to the `CollectionChanged` event and process the changes as needed. – dymanoid Dec 06 '18 at 13:33
  • 1
    `HashSet<>` doesn't look to be easily extendable, but you can always just add a wrapper that implements the mentioned `INotifyCollectionChanged` instead. – icebat Dec 06 '18 at 13:35
  • 1
    You might want to take some inspiration from [QuickGraph](https://github.com/YaccConstructor/QuickGraph) – Magnus Dec 06 '18 at 14:08

1 Answers1

2

I would go with not exposing the HashSet collections directly.

public class Graph : IGraph
{
    private HashSet<INode> _nodes = new HashSet<INode>(); 
    private HashSet<IEdge> _edges = new HashSet<IEdge>();

    public IEnumerable<INode> Nodes => _nodes;
    public IEnumerable<IEdge> Edges => _edges;

    public void AddNode(INode node) => _nodes.Add(node); //Here you can extend with your own custom code.
    public void AddEdge(IEdge edge) => _edges.Add(edge);

    //Here you add other functions such as perhaps "Remove".
}
Magnus
  • 45,362
  • 8
  • 80
  • 118