Question

My code is currently infinity looping and I am not sure why. I am trying to implement a get,set accessor that checks that the accepted number is between 0-100 and if not it will set the value equal to zero. Can't quite put my finger on what I am doing wrong any help would be greatly appreciated.

public double Quiz1
{
    get { return Quiz1; }
    set 
    {
        if (value > 0 && value < 101)
        {
            Quiz1 = value;
        }
        else
        {
            Quiz1 = 0;
        }
    }
}
Was it helpful?

Solution

When you say return Quiz1 inside of the getter, you're recursively calling the getter over and over again.

Auto-Implemented Properties (e.g. public double Quiz1 { get; set; }) provide a hidden field in which the property's value is actually stored.

When implementing traditional (non-auto) get and set methods for a property, there is no auto-generated backing field.

Thus, you typically need to add a backing variable as well:

private double m_quiz1;

public double Quiz1
{
    get { return m_quiz1; }
    set 
    {
        if (value > 0 && value < 101)
        {
            m_quiz1= value;
        }
        else
        {
            m_quiz1= 0;
        }
    }
}

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top