Call (params [] object) using expression []

I am trying to call String.Format from the Linq.Expression tree. Here is a quick example:

var format = Expression.Constant("({0}) {1}"); var company = Expression.Property(input, membernames.First()); var project = Expression.Property(input, membernames.Last()); var args = new Expression[] {format, company, project}; var invoke = Expression.Call(method,args); 

However, the problem is that String.Format has a signature:

 String.Format(string format, params object[] args) 

and I'm trying to pass Expression [].

Now I could solve all the problems of creating an array by filling it with the results of my expressions, but I really want the result to be as follows:

 String.Format("({0}) {1}", input.foo, input.bar) 

How do I access the params function using Linq expressions?

+4
source share
2 answers

In reality, params is just to specify ParamArrayAttribute for this parameter. The C # compiler understands this and creates an array behind the scenes.

Expressions don't understand this, so you really need to create an array yourself if you want to call a method with params . This is also evidenced by the fact that when assigning a lambda expression using the params method, the expression contains the creation of an array:

 Expression<Func<string>> expression = () => string.Format("",1,2,3,4); string expressionString = expression.ToString(); 

Here expressionString will contain this line:

 () => Format("", new [] {Convert(1), Convert(2), Convert(3), Convert(4)}) 

To create an expression that creates an array, use the Expression.NewArrayInit() method.

If you need only two parameters (either one or three), there is an overload of string.Format() , which you can use directly from the expression.

+7
source

params is just syntactic sugar. Ultimately, a parameter is just an array. Therefore, the type of the parameter must be object[] , and the expression describing such an array is what you should pass as the second argument. In other words, you should have only two arguments, not three. The second argument should be a two-element array containing what is currently your second and third arguments.

0
source

All Articles