0

The MSDN documentation on Lamba Expressions provides an example of how to create an expression tree type but it does not show how to use it:

using System.Linq.Expressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<del> myET = x => x * x;
        }
    }
}

Can you complete this console application code so that it actually demonstrates the concept?

2
  • You can compile your expression tree, for sample: del f = myET.Compile(); int j = f(5);. Commented Aug 28, 2015 at 20:29
  • for reference, del is defined earlier in the article to be delegate int del(int i); Commented Aug 28, 2015 at 20:30

1 Answer 1

1

In general Expression Trees contain two parts. A set of parameters and a body. There is only one parameter shown in your example, which is x and the body uses that parameter by multiplying it by itself.

Essentially the behavior setup is something like this:

public int myET(int x)
{
    return x * x;
}

However, in order to access that behavior the value of the Expression must be accessed. This value is a delegate, and is accessed through compiling the expression using .Compile(). Its type will be a Func with the type parameters of your del delegate which were returning int and accepting int.

delegate int del(int i);
static void Main(string[] args)
{
    Expression<del> myET = x => x * x;
    del myFunc = myET.Compile();
}

Once compiled, the function may be called just like the method shown above with the behavior, where a value for the parameter is sent in, and the result of the code in the body is returned.

delegate int del(int i);
static void Main(string[] args)
{
    Expression<del> myET = x => x * x;
    del myFunc = myET.Compile();
    int fiveSquared = myFunc(5);
    Console.WriteLine(fiveSquared);//25
}
Sign up to request clarification or add additional context in comments.

3 Comments

If all you're going to do is compile the expression you'd have been way better off just compiling the lambda as a delegate in the first place.
@Servy - Just trying to show it step by step since it was part of a basic example.
Thanks! But I did have to change your code slightly since the type could not be converted to a System.Function del myDelegate = myET.Compile(); int j = myDelegate(5);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.