This project has moved and is read-only. For the latest updates, please go here.

Sample Expressions

Here are some sample expressions to demonstrate the capabilities of the parser.

Mathematical expressions

By default, numbers without decimals are parsed as integers, and numbers with decimals are parsed as doubles. Mixing different types is allowed, and implicit conversion will be applied between expressions of different types.

   "1 + 2" // returns (int) 3
   "1 + 2d + 2.5" // returns (double) 5.5

Boolean expressions

   "true != false" // returns true

Strings, string concatenation

A single quote ' will have to be escaped as \' which in C# has to be escaped as \\'. A backslash will have to be escaped as \\\\

   "'\\\\Foo' + 'bar' + '\\'s'" // returns \Foobar's

Registered instances, instance member access

   class MyClass
    {
        public double myExternalVar;
        public double getRandomNumber()
        {
            return 4; // chosen by fair dice roll
                         // guaranteed to be random
        }
    }
    
    ...
    
    var v = new MyClass();
    v.myExternalVar = 6;
    var registry = new TypeRegistry();
    registry.RegisterSymbol("vars", v);
    
    // set the TypeRegistry property before eval/compiling
    compiledExpression.TypeRegistry = registry
    ...

   "(vars.myExternalVar + 3) / 2 * 4.5 " // returns 20.25 
   "vars.getRandomNumber()"  // returns a random number

Index accessors

    class MyClass
    {
         public string[] myExternalString;
         public int x;
    }

    var v = new MyClass();
    v.myExternalString = new string[] { "Hello", "there", "World!" };
    v.x = 2;
    ...
    registry.RegisterSymbol("v", v);

   "v.myExternalString[v.x/2]" // returns "there" 

Member accessors

   "'Foobar'.Substring(0,3)" // returns "Foo"
   "v.myStringVar.Substring(0,x)" // returns the first x characters of the string myVarString
   "#Now#.ToString('yyyy/MM/dd hh:mm:ss')" // returns the current time formatted

Last edited Feb 4, 2015 at 12:09 AM by RupertAvery, version 5

Comments

leblanc Feb 27, 2015 at 11:39 PM 
Following statement didn't work:
System.DateTime.Parse(data['ValuationDate']).ToString('yyyy/MM/dd')


with a switch it wouldn't work so had to move to this syntax.
if("{10}".Equals("USD"))
{
data.Result = double.Parse("{19}").ToString();
} else if("{10}".Equals("GBP"))
{
data.Result = (double.Parse("{19}") * 0.65).ToString();
} else if("{10}".Equals("EUR"))
{
data.Result = (double.Parse("{19}") * 0.89).ToString();
}

rollinshultz Jan 17, 2015 at 11:56 PM 
I didn't see anything to handle such expressions as: 2 + 5( 10-2) / (5 - 1) * 2
or expressions as: E x^2 - ((Ex)^2 / n) / n - 1 for calculating standard deviation of a dataset. Are there plans for such features?