user365004
user365004

Reputation: 41

What expression method to use to get back parameter?

Simple question. I am trying to create a basic lambda expression that returns the parameter.

(i, o) => o

I have the first part:

ParameterExpression p1 = Expression.Parameter(relationshipItems.ElementType, "i");
ParameterExpression p2 = Expression.Parameter(instanceEntities.ElementType, "o");

And the last part:

LambdaExpression lambda = Expression.Lambda(p2return, p1, p2);

What method do I use to get back the parameter, presumably as a UnaryExpression(p2return)?

Upvotes: 2

Views: 118

Answers (2)

Sean
Sean

Reputation: 62532

If, for the sake of example, we assume p1 is an int and p2 is a string then this:

var p1=Expression.Parameter(typeof(int),"i");
var p2=Expression.Parameter(typeof(string),"o");

var lambda=Expression.Lambda(p2,p1,p2);
var function=lambda.Compile() as Func<int,string,string>;
var result=function(10,"hello");

will generate a function that returns "o". The lambda will return the value in the last expression in its body, which in the above example is just the parameter p2.

Upvotes: 0

Jeff Mercado
Jeff Mercado

Reputation: 134601

Just set the body to be the second parameter, p2. You already have the reference.

var p1 = Expression.Parameter(relationshipItems.ElementType, "i");
var p2 = Expression.Parameter(instanceEntities.ElementType, "o");
var body = p2;
var lambda = Expression.Lambda(body, p1, p2);

Upvotes: 3

Related Questions