CalculationEngine - shoff/Flee GitHub Wiki

Using the Calculation Engine

The CalculationEngine allows you to create a network of expressions. The engine allows expressions to reference the results of other expressions in the engine, tracks dependencies, and recalculates in natural order.

// Create the calculation engine
CalculationEngine engine = new CalculationEngine();
ExpressionContext context = new ExpressionContext();
VariableCollection variables = context.Variables;

// Add some variables
variables.Add("x", 100);            
variables.Add("y", 200);

// Add an expression to the calculation engine as "a"
engine.Add("a", "x * 2", context);

// Add an expression to the engine as "b"
engine.Add("b", "y + 100", context);
            
// Add an expression at "c" that uses the results of "a" and "b"
engine.Add("c", "a + b", context);
            
// Get the value of "c"
int result = engine.GetResult<int>("c");

// Update a variable on the "a" expression            
variables["x"] = 200;

// Recalculate it
engine.Recalculate("a");

// Get the updated result
result = engine.GetResult<int>("c");

Another example

Here is an example project that shows how to use the CalculationEngine to implement a simple templating system. It reads a template file which has marked up tags such as Mr. <FullName>, you owe <Debt>. Once all the tags are loaded, it asks the user to enter an expression for each tag. Since we are using the calculation engine, the expression for each tag can reference the result of other tag expressions. Once all the expressions are entered, the CalculationEngine does a recalculate. The program then substitutes the result of each tag into the template and outputs the result.

Last edited Feb 28, 2009 at 1:24 PM by ECiloci, version 13

⚠️ **GitHub.com Fallback** ⚠️