Framework > System Layer > Formula Engine > Formula Engine 
C# 
Copy Code


NVariant res; // create the formula engine NFormulaEngine engine = new NFormulaEngine(); // define the a and b variables engine.Variables.Add("a", new NVariant(10)); engine.Variables.Add("b", new NVariant(20)); // evaluate an expression (res is 50) res = engine.ParseAndEvaluate("a+b*2"); // evaluate another expression (res is 40.5) res = engine.ParseAndEvaluate("20.5+(10*2)*COS(0)"); 
Visual Basic 
Copy Code


Dim res As NVariant ' create the formula engine Dim engine As New NFormulaEngine ' define the a and b variables engine.Variables.Add("a", New NVariant(10)) engine.Variables.Add("b", New NVariant(20)) ' evaluate an expression (res is 50) res = engine.ParseAndEvaluate("a+b*2") ' evaluate another expression (res is 40.5) res = engine.ParseAndEvaluate("20.5+(10*2)*COS(0)") 
Following is some background information about the way in which the formula engine works.
Expressions are constructed from tokens. Tokens are such substrings from the initial expression, which cannot be broken into other tokens. A lexically correct expression consists of correct tokens. Currently recognized are the following types of tokens:
An identifier is such a substring from the expression, which starts with a letter or the '_' char and is followed by a sequence of letters, digits or the '_', '.' and '!' characters.
The process of cracking the expression to a list of tokens is called tokenization (lexical analysis). The formula engine performs the tokenization internally and uses its output to build a formula elements tree (grammatical analysis). You can use the Parse method of the NFormulaEngine to obtain the root of the formula elements tree (the elements of this tree are discussed later in this topic).
The evaluation of the formula elements tree uses variants. Variants are represented by the NVariant class. In essence this a valuetype pair, which facilitates the type conversion of values, as well as arithmetic and comparison operations with values of different type. The result of a formula evaluation is a variant (e.g. a value of certain type  see Variants for more information).
Each grammatically correct expression can be represented as a tree of formula elements. All types of formula elements derive from the base NFormulaElement class. A formula expression can contain one of the following formula elements: