tags:

views:

157

answers:

7

I wrote this code:

public static bool MyMethod(int someid, params string[] types)
{...}

How could I write that using Func?

public static Func < int, ?params?, bool > MyMethod = ???
+1  A: 

i'm afraid you couldn't do that.

http://msdn.microsoft.com/en-us/library/w5zay9db%28VS.71%29.aspx

nilphilus
A: 

I don't think there's a way to declare functions through Func... although you can just do:

public static bool MyMethod(int someid, params string[] types) {...}
public static Func < int,params string[], bool > MyFunc = MyMethod;
Dasuraga
+3  A: 

Short answer, you can't, if you really want to preserve the params functionality.

Otherwise, you could settle for:

Func<int, string[], bool> MyMethod = (id, types) => { ... }

bool result = MyMethod(id, types);
Benjol
A: 

I think you want a Func declaration as such:

public static Func<int, string[], bool> MyMethod = ???
Matthew Ruston
+7  A: 

The params keyword is compiled to an ordinary parameter with the ParamArray. You cannot apply an attribute to a generic parameter, so your question is impossible.

Note that you could still use a regular (non-params) delegate:

Func<int, string[], bool> MyMethodDelegate = MyMethod;

In order to use the params keyword with a delegate, you'll need to make your own delegate type:

public delegate bool MyMethodDelegate(int someid, params string[] types);

You could even make it generic:

public delegate TResult ParamsFunc<T1, T2, TResult>(T1 arg1, params T2[] arg2);
SLaks
OK, I take it back, it can be done, nice solution :)
Benjol
A: 

Thanks guys, I think I am gonna use a "normal" method in that case. :-)

grady
You should accept an answer by clicking the hollow check.
SLaks
A: 

How about some helper methods like these?

public static TResult InvokeWithParams<T, TResult>
(this Func<T[], TResult> func, params T[] args) {
    return func(args);
}

public static TResult InvokeWithParams<T1, T2, TResult>
(this Func<T1, T2[], TResult> func, T1 arg1, params T2[] args2) {
    return func(arg1, args2);
}

Obviously, you could implement this for additional generic overloads of Func (as well as Action, for that matter).

Usage:

void TestInvokeWithParams() {
    Func<string[], bool> f = WriteLines;

    int result1 = f.InvokeWithParams("abc", "def", "ghi"); // returns 3
    int result2 = f.InvokeWithParams(null); // returns 0
}

int WriteLines(params string[] lines) {
    if (lines == null)
        return 0;

    foreach (string line in lines)
        Console.WriteLine(line);

    return lines.Length;
}
Dan Tao