Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I take an existing function and write it using Func<..> in C#?

Tags:

c#

delegates

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 = ???
like image 350
grady Avatar asked Apr 16 '10 13:04

grady


3 Answers

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);
like image 116
SLaks Avatar answered Nov 04 '22 16:11

SLaks


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);
like image 22
Benjol Avatar answered Nov 04 '22 17:11

Benjol


i'm afraid you couldn't do that.

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

like image 1
nilphilus Avatar answered Nov 04 '22 16:11

nilphilus