Search code examples
c#expression-trees

difference between delegates and variables in expression trees


I am trying to see if understand expression trees and can generate some of the other supported operators. I don't see why I can not use the plusEqual literal as a function and pass a value to it. I get an error message when I take the comments off. The error says that "Method name expected". My understanding of this code is that plusEquals is a variable, which points to a executable code. I do see that I may be answering part of the question, but my question is why this is happening and that it is contrary to what I have seen in some tutorial sites such as Exprssion Tree basics. Here Charlie has `int c = function(3, 5); I am following the exact steps in creating the plusEquals in my code below. As you see, once I compile() the expression, I get the result I want. Here is my code:

using System;
using System.Linq.Expressions;
namespace myExpressionTree
{
    class Program
    {
        static void Main(string[] args)
        {

            Expression<Func<int, int, int>> expression = (a, b) => a + b;

            Console.WriteLine(expression);
            Expression<Func<int, bool>> lessThan = i => i < 5;
            Console.WriteLine(lessThan);
            Console.WriteLine("result of expression of i < 5 = {0}", lessThan);
            Expression<Func<int, int>> plusEquals = a =>  +a;
            Console.WriteLine(plusEquals);
            //Int32 c = plusEquals(3);
            int c = plusEquals.Compile()(3);
            Console.WriteLine("Here is result of plusEquals expression on c {0}",c);
            Console.ReadLine();
        }
    }

}

` The other interesting point or rather discrepant is the node type displayed in ExpressionVisualizer for plusEquals is lambda rather than they class member name such as Add, lessThan, and others in the Expression. enter image description here

Update; ok got it, and thank you. One outstanding question I have is how come the nodetype for the add expression shows as Add in the ExpressionVisualizer but lessThan and += operator nodetypes are labled as lambda? Add Expression


Solution

  • An Expression is only a representation of a code structure, to execute an Expression you always have to compile it first.

    Look at the Compiling an Expression: Converting Data back into Code section in the link you posted in your question.