Reputation: 629
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?
Upvotes: 0
Views: 181
Reputation: 82267
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
}
Upvotes: 1