Evaluating multiple expressions with same instance of Expression object...

Sep 1, 2010 at 10:28 AM

Hi,

Is there a way to re-use the same instance of Expression object for evaluating multiple expressions one after the other. I think I am looking for something as shown below:

object oValue = null;

Expression myEvaluator = new Expression();

oValue = myEvaluator.Evaluate("a + b");
oValue = myEvaluator.Evaluate("c + d");
oValue = myEvaluator.Evaluate("a + b * xyz");

In my application, I need to evaluate multiple expressions on the same parameter set, but as the expression needs to be supplied through the constructor, I am forced to repeatedly create and destroy the Expression object.

Regards,

- Vikram

Sep 6, 2010 at 11:18 AM

Hey viklele,

there is no way to do with as is.

you have two options:

1) create a wrapper expression factory which creates expressions with a specific parameter dictionary and evaluation options [i've found this useful before]

2) modify the Expression Class to expose the

  protected string expression;
method - be careful then to ensure that you call Compile on set 
David
Sep 6, 2010 at 12:17 PM

Hi David,

Since I didn't want to *modify* Expression class (I avoid doing that in third party components - unless my change is likely to get propagated in the original source), instead I derived from it. Here is what I did:

class MyExression : Expression 
{
   public object Evaluate(string expression)
   {
      string oldExpresion = this.expression; 
      try {
         this.expression = expression; this.Evaluate (); 
      } 
      finally {
         this.expression = oldExpression; 
      }
   }
}

Unfortunately this did not work, as  Evaluate() method has following code:

 

 
if (HasErrors())
{
   throw new EvaluationException(Error);
}

if (ParsedExpression == null)
{
   ParsedExpression = Compile(expression, (Options & EvaluateOptions.NoCache) == EvaluateOptions.NoCache);
}

ParseExpression setter is private, so I cannot clear it.

So, as I don't want to modify Expression class, this now leaves me with the option of factory as you suggested - my only concern is that I need to evaluate hundreds of expressions on same parameter value set, so I will needs as many instances of Expression object :-(

Anyways, thanks for your suggestion.

Regards,

- Vikram

 

 

 

 

 

 

ParsedExpression