Compare object properties using a dynamic operation

I have 2 type object variables that need to be compared using a dynamic enumeration-based operation:

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

You can make the assumption that the basic type of variables is the same, it can only be of type string or any other type of value, but it is unknown at design 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 compliance at runtime (C # 4.0)?

+4
source share
1 answer

Do you have this in a generic method or can you put it in a generic method? If so, then it is relatively simple: use EqualityComparer<T>.Default for equality comparisons and Comparer<T>.Default for larger or smaller than comparisons (using < 0 or <= 0 for less than vs less or equal, for example )

If you cannot call it directly in a generic way, you can use C # 4 dynamic typing to do this 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 run time, this will work out the correct type argument to use for CompareImpl .

+2
source

All Articles