For readability, you may prefer the sentence in the comment:
adjustValue = Value; if (amount < 0) adjustValue -= (ulong)(-amount); else adjustValue += (ulong)amount;
This clearly shows how you expect math to work.
However, & hellip;
The representation of integers in almost every modern hardware CPU is two additions. One of the reasons is that mathematics using two additional binary numbers has a very nice property: you get the same binary representation for addition and subtraction, regardless of whether you have signed or unsigned values.
This means that you can simply change the adjustment value to ulong to make your addition. According to C # language rules, a translation will simply reinterpret the binary representation of the signed value as unsigned. And adding an unsigned value will have exactly the same effect as if you added a signed value with the same binary representation.
Here is an example of code that shows that this works:
static void Main(string[] args) { ulong[] values = { ulong.MinValue, ulong.MaxValue, long.MaxValue }; long[] adjust = { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < adjust.Length; j++) { ulong value = values[i]; bool result = AdjustValue(adjust[j], ref value); Console.WriteLine($"{values[i]} + {adjust[j]} = {values} (overflow: {!result})"); } } } static bool AdjustValue(long amount, ref ulong value) { ulong adjustValue = value + (ulong)amount; if (amount < 0 && adjustValue > value) return false; if (amount > 0 && adjustValue < value) return false; value = adjustValue; return true; }
Note. By default, math operations are performed without verification. However, there is a compiler that can change this. If you compile your code with this switch turned on, forcing checked arithmetic operations, you need to wrap this in an unchecked block to avoid getting overflow exceptions.
source share