Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func<> with unknown number of parameters

Tags:

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?

like image 524
user2341923 Avatar asked Apr 03 '14 09:04

user2341923


People also ask

What is func t TResult?

Func<T, TResult> defines a function that accepts one parameter (of type T) and returns an object (of type TResult).

How Func works in c#?

Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.

How can you get the type of arguments passed to a function?

There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.

Can a Python function take unlimited number of arguments?

Unlimited Number of Positional Argument ValuesPython lets us define a function that handles an unknown and unlimited number of argument values. Examples of built-in functions with a unlimited number of argument values are max and min .


2 Answers

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);
like image 137
dcastro Avatar answered Oct 20 '22 19:10

dcastro


You can use Delegate with DynamicInvoke.

With that, you don't need to handle with object[] in f.

TResult Foo<TResult>(Delegate f, params object[] args)
{
    var result = f.DynamicInvoke(args);
    return (TResult)Convert.ChangeType(result, typeof(TResult));
}

Usage:

Func<string, int, bool, bool> f = (name, age, active) =>
{
    if (name == "Jon" && age == 40 && active)
    {
        return true;
    }
    return false;
}; 

Foo<bool>(f,"Jon", 40, true);

I created a fiddle showing some examples: https://dotnetfiddle.net/LdmOqo


Note:

If you want to use a method group, you need to use an explict casting to Func:

public static bool Method(string name, int age)
{
    ...
}
var method = (Func<string, int, bool>)Method;
Foo<bool>(method, "Jon", 40);

Fiddle: https://dotnetfiddle.net/3ZPLsY

like image 45
Renan Araújo Avatar answered Oct 20 '22 19:10

Renan Araújo