Wednesday, 21 August 2013

C# Elegant way for retaining sign of original int/double variable after operations

C# Elegant way for retaining sign of original int/double variable after
operations

Is there a clever way to retain the sign of an integer/double variable
after performing a bunch of operations on it? By elegant I'm probably
looking more at bitwise operation or some sort of function to retain the
sign.
Here's what I'd call the not-so-elegant way:
int myNum = -4;
bool isNegative = myNum < 0 ? true : false;
myNum += 8 / 2 % 4; //some operation
if ((isNegative && myNum > 0) || (!isNegative && myNum < 0))
myNum *= -1;

No comments:

Post a Comment