Weird setter functionality?
This is essentially what I have:
private float health;
public float Health {
set {
health += value;
}
}
. . .
health -= 100;
For some reason, instead of getting the health and subtracting 100, it will add 100.
Answer by Dave-Carlile · Dec 19, 2015 at 02:18 AM
The last line isn't using the setter at all, it's just subtracting 100 from health
. To use the setter you would need to use Health -= 100
. I think something is missing in the code you posted. In fact, trying to use the property in that way generates the error "The property cannot be used in this context because it lacks a get accessor". Adding the get so it compiles results in -100 as expected. Now, if health starts out as a value other than 0 then you will have some odd behavior as outlined next.
Don't do that sort of thing in a setter. The expected behavior is to set something to the value of an expression. Your code will lead to some very, very confusing behavior, for example...
Health = 0;
Health += 10;
Health += 10;
Health += 10;
Health += 10;
Using your setter, what is the value of Health when that is done? Any sane person would say 40. However it's not, it's 150. Why?
First, remember that Health += 10
is the same as Health = Health + 10
. And your setter is health = health + value
. Combining those, each line is health = health + (health + 10)
.
Health = 0; // health is 0
Health = Health + 10; // health = 0 + (0 + 10), health = 10
Health = Health + 10; // health = 10 + (10 + 10), health = 30
Health = Health + 10; // health = 30 + (30 + 10), health = 70
Health = Health + 10; // health = 70 + (70 + 10), health = 150
That is completely unexpected and non-intuitive behavior. Don't do it. The setter should be health = value
. If you want something to increment then make a function...
void AddHealth(float value)
{
health += value;
}
That is intuitive.
Wow, thanks.. I'm not thinking straight sometimes.
By the way, the health+=
was a typo, I meant Health
(capital H). Thank you!