Is it possible to have a C# lambda/delegate that can take a variable number of parameters that can be invoked with a Dynamic-invoke?
All my attempts to use the ‘params’ keyword in this context have failed.
UPDATE WITH WORKING CODE FROM ANSWER:
delegate void Foo(params string[] strings);
static void Main(string[] args)
{
Foo x = strings =>
{
foreach(string s in strings)
Console.WriteLine(s);
};
//Added to make it clear how this eventually is used :)
Delegate d = x;
d.DynamicInvoke(new[]{new string[]{"1", "2", "3"}});
}
The reason that it doesn’t work when passing the arguments directly to
DynamicInvoke()is becauseDynamicInvoke()expects an array of objects, one element for each parameter of the target method, and the compiler will interpret a single array as the params array toDynamicInvoke()instead of a single argument to the target method (unless you cast it as a singleobject).You can also call
DynamicInvoke()by passing an array that contains the target method’s parameters array. The outer array will be accepted as the argument forDynamicInvoke()‘s single params parameter and the inner array will be accepted as the params array for the target method.