There are already solutions to this problem for small numbers:
- Here: Difference between 2 numbers
- Here: C# function to find the delta of two numbers
- Here: How can I find the difference between 2 values in C#?
I'll summarise the answer to them all:
Math.Abs(a - b)
The problem is when the numbers are large this gives the wrong answer (by means of an overflow). Worse still, if (a - b) = Int32.MinValue
then Math.Abs
crashes with an exception (because Int32.MaxValue = Int32.MinValue - 1
):
System.OverflowException occurred
HResult=0x80131516
Message=Negating the minimum value of a twos complement number is invalid.
Source=mscorlib
StackTrace: at System.Math.AbsHelper(Int32 value) at System.Math.Abs(Int32 value)
Its specific nature leads to difficult-to-reproduce bugs.
Maybe I'm missing some well known library function, but is there any way of determining the difference safely?
See Question&Answers more detail:os