65.9K
CodeProject is changing. Read more.
Home

Ad-Hoc Expression Evaluation

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jul 26, 2012

CPOL
viewsIcon

10499

This is an alternative for "Ad-Hoc Expression Evaluation"

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;
 
        // Just to make our comparisons easier.
        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.