Is there a way in C# to pass a single array as separate arguments (parameters) to a function?
Given the following super simplified example:
Func<int, int, int> sum = (int a, int b) => { return a + b; };
// sum(1, 2); This would work and return 3
sum([1,2]); // This is how I would like to call it
Is there a way to make last line work?
Note: I know that you could make a delegate take a single int[]
as an argument, but in my real use case modifying a delegate is not possible.
Note 2: In real use case parameters are not of the same type. It could be a mixture of int
, string
, object
, etc.
If it helps, in PHP this could be achieved with call_user_func_array()
. Example
UPDATE: Real use case is that I want to have a single function that receives a delegate and all required parameters. So instead of having to write out all different cases like below:
public void OneParam<T1, TOut>(Func<T1, TOut> func, T1 p1)
{
// Do some fancy stuff before calling
func.Invoke(p1);
}
public void TwoParam<T1, T2, TOut>(Func<T1, T2, TOut> func, T1 p1, T2 p2)
{
// Do exact same some fancy stuff before calling
func.Invoke(p1, p2);
}
I would like to have just a single function that takes any delegate with any amount of parameters and then eventually to be able to pass those parameters into a delegate.
TL;DR answer: As per @gunr2171 answer this is not possible. I wanted the opposite of params
, which is not achievable. This probably make sense as C# creators also had to type out all different delegates with different amount of parameters manually as well.