I have a class which represents a shape. The Shape class has a property called Angle. I want the setter for this property to automatically wrap the value into the range [0,359].
Unfortunately, a simple _Angle = value % 360;
only works for positive numbers. In C#, -40 % 360 == -40
. Google calc does it the way I want it. The value should be 320.
What's the most elegant solution in C#?
Here's the best way I've got so far:
public double Angle {
get { return _Angle; }
set {
if ( value >= 0 ) {
_Angle = value % 360;
}
else {
_Angle = value - (360 * ((int)(value / 360) - 1));
}
}
}
Edit:
Thanks guys, I now have:
public double Angle {
get { return _Angle; }
set {
_Angle = (value % 360) + ((value < 0) ? 360 : 0);
}
}
..Which is a lot better :)