Question

I want to compare two values at runtime using reflection. I was using Comparer.Default.Compare(x,y) for this, but I have come to realize that this is not adequate. Let's say I want to compare a double to a single (1.0 == 10). Comparer.Default will throw an exception because it insists that both values must be the same type (double). However, an explicit conversion exists for this, which is really what I want to use.

So, why can't I just use Convert.ChangeType? Take the case of 1.25 > 1 (double > integer). If I try Convert.ChangeType(1.25,typeof(int)) on 1.25, I will get 1, and the assertion above will fail, when really 1.25 IS > 1.

So, can someone please suggest a way of invoking the explicit comparison (if it exists) that a type defines?

Thanks.

Was it helpful?

Solution

Are you using C# 4 and .NET 4? If so, it's really easy using dynamic typing:

dynamic x = firstValue;
dynamic y = secondValue;
if (x > y) // Or whatever

The compiler performs all the appropriate conversions for you.

OTHER TIPS

If C# 4 is an option, Jon Skeet's suggestion of using dynamic is most likely ideal.

If it is not, then...

There isn't an explicit comparison. The compiler, at compile time, does the conversion, then invokes the appropriate comparison.

Your best bet is to use Convert.ChangeType to convert to the wider type, and then do the comparison on the result. If you don't want to handle checking of all types, you can typically convert both sides to decimal values, then use a single comparison to check them, as decimal should handle all of your values adequately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top