Search code examples
c#accessor

Using accessors in C# stack overflow


From http://msdn.microsoft.com/en-us/library/aa287786(v=vs.71).aspx

public string Name { get { return name; } set { name = value; } }

So why is it that when I set the value as so:

public int numHighAttacksHit
        {
            get { return numHighAttacksHit - handicapHighAttacks; }
            set { numHighAttacksHit = value; }
        }

this.numHighAttacksHit = 0;

It keeps circling around again and again setting value to numHighAttacksHit until I reach a stack overflow? This is within the same class, does that matter?

screenshot: http://gyazo.com/a49757753acfbb5b51aaef5be033c948.png


Solution

  • The property needs a field to reference, like this:

    private int numHighAttacksHit;
    public int NumHighAttacksHit   // <-- note the pascal case
        {
            get { return numHighAttacksHit - handicapHighAttacks; }
            set { numHighAttacksHit = value; }
        }
    
    this.NumHighAttacksHit = 0;