Hi folks,
I have defined a C#-class, that shall be the elements of a directed graph (basically a tree, but an element can have multiple parents - I do not know if there is a special name for that).
Each element shall now all its children and all its parents. It exposes those lists as IEnumarable
public interface IMyClass
{
public IEnumerable<MyClass> Children { get; }
public IEnumerable<MyClass> Parents { get; }
}
public class MyClass : IMyClass
{
private List<MyClass> _parents;
private List<MyClass> _children;
public IEnumerable<MyClass> Children
{
get { foreach (var child in _children) yield return child; }
}
public IEnumerable<MyClass> Parents
{
get { foreach (var parent in _parents) yield return parent; }
}
When adding or removing a child to a given element, I want to make sure, that the given element is added or removed to the parents list of the child too.
First idea was to only expose an AddChild(MyClass theChild) method. Problem is, that I can't add the parent to the theChild object because it doesn't expose an AddParent(parent) method and I can't call private methods of the theChild-object.
So I tried to go with exposing an AddParent(MyClass theParent) method too. To still make sure that both objects links are set, my first shot was calling the AddParent/AddChild in the other function like this:
public void AddChild(IMyClass theChild)
{
_children.Add(theChild);
theChild.AddParent(this);
}
public void AddParent(IMyClass theParent)
{
_parent.Add(theParent);
theParent.AddChild(this);
}
but obviously, that is a deadly loop.
To make things worse, I want to allow that an element can be the child of another element multiple times (this isn't a requirement yet, but I want to make sure, that WHEN this requirement comes, my code need not to be touched.)
Are there any algorithms / standard approaches that allow me to make sure, that when adding a child to the parent always both object links are set?
Thanks in advance,
Frank
Edith: Added the interfaces to correct the example.