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) ?
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>.Defaultfor the equality comparisons, andComparer<T>.Defaultfor greater than / less than comparisons (using a< 0or<= 0for 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:
At execution time, that will work out the right type argument to use for
CompareImpl.