Using the Code
JSOP's initial tip was to perform the following:
- Compare two objects of the same type
- Use a
string
to determine what sort of comparison would take place
The initial solution converted each object into a known type (string
, decimal
, or DateTime
) prior to performing a comparison. Using the CompareTo<T>
interface, the code JSOP provided could be significantly simplified. The following is the JSOP's Evaluator rewritten to use generics:
public static class GenericEvaluator
{
public static bool Evaluate<T>(string comparison, T obj1, T obj2) where T : IComparable<T>
{
bool result = false;
comparison = comparison.ToUpper();
if ((comparison == "AND") || (comparison == "OR"))
{
if (obj1 is bool)
{
if (comparison == "AND")
result = ((bool)(object)obj1 && (bool)(object)obj2);
else
result = ((bool)(object)obj1 || (bool)(object)obj2);
}
}
else
{
int compareTo = obj1.CompareTo(obj2);
switch (comparison)
{
case "EQUAL": result = (compareTo == 0); break;
case "NOT EQUAL": result = (compareTo != 0); break;
case "GREATER THAN": result = (compareTo > 0); break;
case "LESS THAN": result = (compareTo < 0); break;
case "GREATER THAN OR EQUAL": result = (compareTo >= 0); break;
case "LESS THAN OR EQUAL": result = (compareTo <= 0); break;
}
}
return result;
}
}
Further improvements could be made by using something other than a string
to determine which comparison is made, but I decided to keep with the original requirements JSOP provided.