Question

I working on a code that is written by someone else, and stuck because of a problem which I think has something to do with a setter method. The code below tries to assign a true value to a public element whose access is controlled by a setter element.

        while (true)
        {
            currentN = currentN.Pass(d);
            if (currentN.NID == aimedID)
            {
                currentN.IsValid = true;
                break;
            }
        }

When I debug the code, it is incredible for me to see even in the cases it enters into the if condition, it does not assign the value true to the currentNode.IsValid variable. It remains as it was before (false).

The getter/setter methods are given below:

 public bool IsValid 
    {
        get { return Branches == null || Branches.Length == 0; }
        set {}
    }

As I said above, I think this has something to do with the setter method. If I do not write anything for the set part, I cannot assign a value to the IsValid variable. If I write set { this.IsValid = value}, it ends up with a stackoverflow error. Assigning a value for IsLeaf should not be this hard. I guess I am missing a point, although I checked some tutorials about getter/setter methods.

How should I alter the setter method so that I can assign a value to IsValid property?

Thanks.

Was it helpful?

Solution

This is because you do absolute nothing in the setter, and if you do IsValid = true then you're assigning the thing to itself, which naturally goes in circles. You should remove the setter since the getter relies on peripheral information and isn't a standalone value.

For the condition to be true, Branches needs to have some items.

OTHER TIPS

Usually, you don't want to set a value for the IsValid property because it's meant to be read, not set. Just leave out the set {} accessor, you don't need it:

public bool IsValid 
{
    get { return Branches == null || Branches.Length == 0; }
}

You could also encapsulate the validation logic in a method:

public bool IsValid()
{
    return Branches == null || Branches.Length == 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top