What is the difference between the static methods Int32.Min
and Int32.MinMagnitude
, that were introduced in .NET 7? Their signature and description is the same:
// Compares two values to compute which is lesser.
public static int Min (int x, int y);
// Compares two values to compute which is lesser.
public static int MinMagnitude (int x, int y);
MinMagnitude()
compares the absolute values of the inputs. When x
and y
are positive, it works exactly like Min()
. If either or both of them are negative then the sign(s) will be ignored for the comparison, but are kept on the return value.
Some examples:
Debug.Assert(int.MinMagnitude( 10, 1) == 1);
Debug.Assert(int.MinMagnitude(-10, 1) == 1);
Debug.Assert(int.MinMagnitude( 10, -1) == -1);
Debug.Assert(int.MinMagnitude(-10, -1) == -1);
One special case is when comparing numbers of equal absolute value, but different sign. Then it returns the negative of the common absolute value:
Debug.Assert(int.MinMagnitude(-1, 1) == -1);
Debug.Assert(int.MinMagnitude( 1, -1) == -1);
Have a look at the source code here.