Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare numeric types when types are unknown

Tags:

c#

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).

like image 220
Matt Burland Avatar asked Apr 23 '26 07:04

Matt Burland


1 Answers

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
like image 181
Sriram Sakthivel Avatar answered Apr 25 '26 04:04

Sriram Sakthivel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!