Triynko
Triynko

Reputation: 19194

Can I pass an array of lambda expressions to a method with a params argument?

I want to call a method like this:

signature: void Method(object a, object b, params LambdaExpression[] expressions);

call: Method(a, b, x => x.A, x => x.B)

Is it possible?

Let's assume that the type of 'x' is a constant type. For example, if x => x.A and y => y.B were Funcs, they'd be Func<TType,*>, such that the params array always had the same type for TType, but the return value's type * could differ from element to element of the params array. That's why I had to choose something more generic like LambdaExpression as the type, but I don't know if that will work. I can unpack the expression within the method at runtime, but I'm having a hard time just trying to pass expressions to a method when one of their two generic type parameters differ.

It would be fine, even if I had to call it more like: Method(a, b, (Type x) => x.A, (Type x) => x.B)

Upvotes: 1

Views: 1756

Answers (1)

Ventsyslav Raikov
Ventsyslav Raikov

Reputation: 7202

You can but the compiler assist that will turn your code to expression(vs compiling it) works with generics only. So you have to

Expression<Func<TType, AType>> expr1 = x => x.A;
Expression<Func<TType, BType>> expr2 = x => x.B;

Method(a, b, expr1, expr2);

or cast inline

Method(a, b, (Expression<Func<TType, AType>>) (x => x.A), expr2)

or use a more generic type of argument

void Method(object a, object b, params Expression<Func<object, object>>[] expressions)

Upvotes: 4

Related Questions