Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Ad-Hoc Expression Evaluation

0.00/5 (No votes)
25 Jul 2012 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here