0

I have a class Node:

class Node
{
    public string Name { get; private set; }
    public Node Parent { get; private set; }

    ... // some more fields and methods
}

At the start of my program, I have some Node objects whose Parent fields are all null. During the course of my progam, all of the nodes except one will get a parent set. But since it depends on external factors, I don't know when this will happen.

Now I have some Node A and want to run the following code:

Node n = A;
while (!n.HasCertainProperty()) // some method returning a bool
    n = n.Parent;
DoStuffWith(n); // some method processing n

How can I delay the command n = n.Parent until n.Parent is not null any more?

(My algorithm is so that n will never be the one Node that does not get a parent; i.e. it is guaranteed that n.Parent != null will be true at some point in the future.)


Here is a solution sketch of mine:

First we modify the Node class by adding an event mechanism:

class Node
{
    public string Name { get; private set; }

    public event EventHandler OnParentSet;

    private Node _parent;
    public Node Parent
    {
        get { return _parent; }
        private set
        {
            _parent = value;
            OnParentSet?.Invoke(this, EventArgs.Empty);
        }
    }

    ... // some more fields and methods
}

Then we use the following two methods in place of the code from above:

void MyMethod(Node A)
{
    Node n = A;
    if (n.HasCertainProperty())
        DoStuffWith(n);
    else
    {           
        if (n.Parent == null)
            A.OnParentSet += (o, e) => { RunWhenParentIsSet(n); };
        else
            RunWhenParentIsSet(n);
    }
}

void RunWhenParentIsSet(Node n)
{
    n = n.Parent;
    MyMethod(n);
}

But I don't like this solution because I had to transform the while loop into a recursion. Isn't there a way to more or less keep the original code without the need for transformation?

Kjara
  • 2,504
  • 15
  • 42

0 Answers0