Given you have the following class (bad C#, but you get the drift):
public abstract class AmICircular
{
// assume Children is never null
private List<AmICircular> Children {get;set;}
// assume target is never null
public void Add(AmICircular target)
{
target.PerformCircularReferenceCheck(this);
Children.Add(target);
}
// throws when a circular reference is detected
protected abstract void PerformCircularReferenceCheck(AmICircular target);
}
How would you implement PerformCircularReferenceCheck? And, no, this isn't homework.
The naive implementation, imo, would be to do a reference check on this
and all children, then call PerformCircularReferenceCheck on target
, passing this
. But I'm wondering if there are better, proven effective, ways to do this, such as adding a method to collapse the entire Children tree of references for this
and target
and then examine the results (less pressure on the stack?), or perhaps avoid the check entirely by using a different (maybe self-checking!) collection other than List<T>?
How would you do this?
edit: As stefan pointed out, it is only necessary to determine if this is reachable by the target