Comparison of two variables with the same value, but the type is different (for example, Int16, Int32, Int64)

I need to compare two variables to find if they are the same. These variables are passed as an “object” and can be assigned to any type of .NET.

The problem I am facing is if they are both numbers. In situations where they have the same value (for example, they are -1), but have different types (for example, one of them is Int32, the other is Int64), then object.Equals returns false.

Is there a reasonable general way to compare values ​​that ignore the type of a variable and only look at a numeric value?

+5
source share
4 answers

, , , Convert.ToInt64 longs, ==. , UInt64.

+2

, ==, < .. Int16 Int32, . Int * - , .

+1

, , object, , long. ( ), 2 ints , .

Another, somewhat hacky option is to call ToString () on both and compare strings. This will only work if they are both integral types (i.e. No doubleor decimal), so you should check the types in advance.

0
source

I was able to use the System.IConvertible interface to solve this problem for value types:

object expectedValue = (int) 42;
object testValue = (long) 42;

// This handles equal values stored as different types, such as int vs. long.
if (testValue is IConvertible testValueConvertible
    && expectedValue is IConvertible)
{
    testValue = testValueConvertible
        .ToType(expectedValue.GetType(),
                System.Globalization.CultureInfo.InvariantCulture);
}

if (object.Equals(testValue, expectedValue))
    Console.WriteLine("Values are equal");
else
    Console.WriteLine("Values are NOT equal");

I created this .NET script as a demo: https://dotnetfiddle.net/GSUjIS

0
source

All Articles