I have two values that I want to compare:
var value1 = someProperty.GetValue(x);
var value2 = someOtherProperty.GetValue(y);
if (value1 == value2)
{
// do something
}
where someProperty and someOtherProperty are PropertyInfo objects. In other words, I'm getting the values by reflection.
The problem is if value1 ends up being an int with the value 4, and value2 ends up being a byte with value 4, I'd like to be able to tell those are the same. Is there a method to compare two numeric values without regard to their type? Preferably one that would still allow be to, say, compare two strings (so I can't really cast value2 to int because it might turn out that it's a string).
One option is to use dynamic. This will make compiler to emit dynamic call site and asks the DLR to kick in to compare the objects at runtime.
object obj1 = (int)4;//Default is int, but added to make intent clear
object obj2 = (byte)4;
Console.WriteLine(obj1 == obj2);
Console.WriteLine((dynamic)obj1 == (dynamic)obj2);
Prints
False
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With