tags:

views:

17

answers:

1

I have 2 variables of type object that needs to be compared using a dynamic operation that is based on an enum:

public enum OperationType
{
    None,
    EqualTo,
    NotEqualTo,
    GreaterThan,
    GreaterThanOrEqualTo,
    LessThan,
    LessThanOrEqualTo          
}

You can make the assumption that the underlying type of the variables are the same, can only be of type string, or any other value type, but are unknown during development time.

I currently have the following:

 bool match;
 switch (Operation)
 {
      case OperationType.EqualTo:
           match = Equals(targetValue, valueToMatch);
           break;
      case OperationType.NotEqualTo:
           match = Equals(targetValue, valueToMatch) == false;
           break;
      case OperationType.GreaterThan:
           //??
           break;
      case OperationType.GreaterThanOrEqualTo:
           //??
           break;          
      case OperationType.LessThan:
           //??
           break;
      case OperationType.LessThanOrEqualTo:
           //??
           break;          
      default:
           throw new ArgumentOutOfRangeException();
 }

What is the best way to determine a match at runtime (C# 4.0) ?

+2  A: 

Do you have this in a generic method, or could you put it in a generic method? If so, it's relatively easy: use EqualityComparer<T>.Default for the equality comparisons, and Comparer<T>.Default for greater than / less than comparisons (using a < 0 or <= 0 for less-than vs less-than-or-equal-to for example).

If you can't call it directly in a generic way, you could use C# 4's dynamic typing to do it for you:

private static bool CompareImpl<T>(T value1, T value2, OperationType operation)
{
    // Stuff using generics
}

public static bool Compare(dynamic value1, dynamic value2,
                           OperationType operation)
{
    return CompareImpl(value1, value2, operation);
}

At execution time, that will work out the right type argument to use for CompareImpl.

Jon Skeet