C# Get Set Causing Stack Overflow

Hello everyone, I’m having a problem trying to create get/set properties for a variable, but I keep getting a stack overflow error (from the: return Score; line). I’m new to C# so I’m sure its some dumb mistake on my end, but I just am not seeing it.

	public int Score
	{
		get
		{
			return Score;
		}

		set
		{
			if (Score<0){
				Score = 0;
			}
			Score += value;
		}

	}

Update: Thank you to both of you guys- you are both correct about my error. One more follow up question if possible: I made the corrections you both suggested and the error is gone - However, I noticed that when I assigned values to score (after instantiating an object of the class), the += operator doesn’t seem to do anything. For example, if I add 10 to score then print I get 10. But if I then add 20 and print, I just get 20 (not 30). So it seems there is no purpose in using any other operators within the set method?

Your public property should have a different name to your private variable.

What you have now is causing an infinite loop.

Please look at this implementation fixes the infinite loop while preserving your logic :

private int _score;
public int score {
    get {
        return _score;
    }
    set {
        if (_score < 0) {
            _score = 0;
        }
        _score += value;
    }
}

However your logic is a little unorthodox. As it stands your property would exhibit the following behaviour:

score = 10;
Debug.Log(score); //10
score = 10;
Debug.Log(score); //20

I would recommend the more conventional:

private int _score;
public int score {
    get {
        return _score;
    }
    set {
        if (value > 0) {
            _score = value;
        }
        else {
            _score = 0;
        }
    }
}

Then you could consume the property as follows:

score += 10;
Debug.Log(score); //10
score += 10;
Debug.Log(score); //20

Always use lowercase for variable names. Uppercase is for classes and methods. You also need something for your getter and setter to actually work with; they can’t work on the class itself.