Reputation: 49042
I need to compare two variables to find if they are the same. These variables are cast as "object" and could be assigned any .NET type.
The problem I am encountering is if they are both numbers. In situations where they have the same value (e.g. they are both -1) but have different types (e.g. one is Int32, the other is Int64) then object.Equals returns false.
Is there a reasonably generic way to compare values that will ignore the type of the variable and only look at the number value?
Upvotes: 6
Views: 3840
Reputation: 879
I was able to use the System.IConvertible interface to resolve 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 Fiddle as a demonstration: https://dotnetfiddle.net/GSUjIS
Upvotes: 0
Reputation: 1756
Assuming that you have a method that takes two object
parameters, you could create an overload that takes two long
parameters. I believe (though I haven't verified) that passing 2 ints would choose the overload with the longs, rather than the objects.
Another, somewhat hackish, option is to call ToString() on both and compare the strings. This will only work if they're both integral types (i.e. no double
or decimal
), so you'd want to check the types beforehand.
Upvotes: 0
Reputation: 6437
Assuming the types are boxed integers, so you can't simply == them, you might want to use Convert.ToInt64 to convert all the values to longs and then compare them using ==. You'll need extra logic if you want to support UInt64s though.
Upvotes: 3
Reputation: 61437
Simply use the usual operators like ==
, <
etc. Int16 will automatically be casted to Int32 as there is no information loss doing so. Int* are value types, thus the values are compared automatically.
Upvotes: 0