C# language feature:

  • Expression trees

applies to

  • “on the fly/runtime coding”

benefit

  • Allows powerful ability to compile and run code represented by expression trees (code in a tree-like data structure). This enables dynamic modification of executable code,LINQ and dynamic queries. Expression trees API (in .NET Framework 4) also supports assignments and control flow expressions such as loops, conditional blocks, and try-catch blocks. Additionally, expression trees allows for intermediate code analysis to improve execution of a statement. For example, a sql statement with a where clause can be sent to the server for execution in place of pulling data locally and then applying the filtering/where clause.

how to use

  • 1) Create expression 2) Compile and execute

more info

  • For other uses of expression trees, please see https://msdn.microsoft.com/en-us/library/bb397951(v=vs.110).aspx

example:

        void Use_of_Expression_Tree() { 
            // Create and expression tree that subtracts two integers

            // 1)  Create the expression
            ParameterExpression openandLeft = Expression.Parameter(typeof(int), "openandLeft");
            ParameterExpression operandRight = Expression.Parameter(typeof(int), "operandRight");
            ParameterExpression[] parameters = new ParameterExpression[] { openandLeft, operandRight };
            
            BinaryExpression body = GetBinaryMathOperatorExpression('-', openandLeft, operandRight); //Create the expression body
            Expression<Func<int, int, int>> expression = Expression.Lambda<Func<int, int, int>>(body, parameters); //Create the expression
            Func<int, int, int> compiledExpression = expression.Compile(); // Compile the expression
            // 2) Execute the expression. 
            int result = compiledExpression(7, 4); //returns 3

            // alternatively create and execute an expression tree that adds to integers
            body = GetBinaryMathOperatorExpression('+', openandLeft, operandRight);
            expression = Expression.Lambda<Func<int, int, int>>(body, parameters);  //Create the expression 
            compiledExpression = expression.Compile();  // Compile the expression
            // Execute the expression. 
            result = compiledExpression(7, 4); //returns 11

            // A potential use of expression trees is to allow a user specified expression for a calculated field/output
        }

        BinaryExpression GetBinaryMathOperatorExpression(char mathoperator, ParameterExpression opL, ParameterExpression opR)
        {

            switch (mathoperator) { 
                case('+'):return Expression.Add(opL, opR);
                case ('-'): return Expression.Subtract(opL, opR);
                default:
                    throw new NotImplementedException();
            }
        }