Search code examples
c#.netgenericsfunctional-programmingclr

Func<> with unknown number of parameters


Consider the following pseudo code:

TResult Foo<TResult>(Func<T1, T2,...,Tn, TResult> f, params object[] args)
{
    TResult result = f(args);
    return result;
}

The function accepts Func<> with unknown number of generic parameters and a list of the corresponding arguments. Is it possible to write it in C#? How to define and call Foo? How do I pass args to f?


Solution

  • That's not possible. At best, you could have a delegate that also takes a variable number of arguments, and then have the delegate parse the arguments

    TResult Foo<TResult>(Func<object[], TResult> f, params object[] args)
    {
        TResult result = f(args);
        return result;
    }
    


    Foo<int>(args =>
    {
        var name = args[0] as string;
        var age = (int) args[1];
    
        //...
    
        return age;
    }, arg1, arg2, arg3);