Search code examples
c#reflectioniequalitycomparer

Comparison Operator using Reflection


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.


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.