This project has moved. For the latest updates, please go here.

if then else

Aug 9, 2016 at 4:46 AM
Having a basic issue with running statements here but i actually want to run a "if then else" statement

double A, B; A = 0.5; B = 0;
        var registry = new TypeRegistry();
        registry.RegisterSymbol("A", A);
        registry.RegisterSymbol("B", B);

         var expression = new CompiledExpression();
        expression.StringToParse = "B=3;A=6;";
        expression.TypeRegistry = registry;
        expression.ExpressionType = CompiledExpressionType.Statement;       
error in the console window is
" Unhandled Exception: System.ArgumentException: Expression must be writeable
Parameter name: left
at System.Linq.Expressions.Expression.RequiresCanWrite(Expression expression,
String paramName)
at System.Linq.Expressions.Expression.Assign(Expression left, Expression righ
at ExpressionEvaluator.Parser.ExpressionHelper.Assign(Expression le, Expressi
on re, Dictionary`2 dynamicTypeLookup)"

pls help me, if you can provide example of "if then else" statements or statement list , it would be great. Thanks
Sep 15, 2016 at 10:51 PM
Edited Sep 15, 2016 at 10:59 PM
Symbols are not variables, they are compiled as constants, thus they cannot be assigned to. Usually you would create a class to contain the variables.

Also, you should use the ScopeCompile feature to make variables scoped to an instance of a class.

ScopeCompile creates a delegate function has one argument, an instance of the scope type.

Any symbols in the expression that do not match any registered types or symbols are "scoped" to the scope type instance.
    class Container
        public int a { get; set; }
        public int b { get; set; }

    class Program
        static void Main(string[] args)
            var expr = @"
                a = 1; 
                b = 0; 
                if (a == 0) {
                    b = 1; 
                } else {
                    b = 2;

            var container = new Container();
            var expression = new CompiledExpression(expr);
            expression.ExpressionType = CompiledExpressionType.StatementList;
            var func = expression.ScopeCompile<Container>();

            // b == 2

Hope this helps