Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function as a parameter in C#?

Tags:

c#

reflection

Is it possible to pass a function as a parameter in C#? I can do it using the Func or Action classes, but this forces me to declare the entire function signature at once. When I try to use Delegate, I get a compile error saying it can't convert a method group to a Delegate.

I'm working on Axial and I'm trying to allow users to call web services. What I'm going for is the ability to create the Visual Studio proxy class and then pass in the generated function. The function signature doesn't matter because the generated code only uses the function name. However, I'd like to pass in the function instead of the name for two reasons: the ability to use the proxy's Url property and a compiler error if the web service doesn't exist or is updated in Visual Studio.

 public void AlertIt(object o) {     Axial.DOM.Window.Alert(o.ToString()); } public void CallAddService() {     object[] param = new object[] { int.Parse(txtA.Text), int.Parse(txtB.Text) };     Axial.ServerScript.CallWebService(new WSProxy.WS().Add, param, AlertIt, AlertIt); }  class Axial.ServerScript {     public void CallWebService(Delegate method, object[] param, Action<object> successCallback, Action<object> failureCallback) {         // translate to javascript (already working)     } } 
like image 789
Dan Goldstein Avatar asked Dec 19 '08 05:12

Dan Goldstein


People also ask

Can I pass a function as a parameter in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.

Can we pass function as parameter?

Conclusion. Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.

What is parameter passing in C with example?

Parameter passing involves passing input parameters into a module (a function in C and a function and procedure in Pascal) and receiving output parameters back from the module. For example a quadratic equation module requires three parameters to be passed to it, these would be a, b and c.


1 Answers

I think what you want is:

static object InvokeMethod(Delegate method, params object[] args){     return method.DynamicInvoke(args); }  static int Add(int a, int b){     return a + b; }  static void Test(){     Console.WriteLine(InvokeMethod(new Func<int, int, int>(Add), 5, 4)); } 

Prints "9".

like image 70
P Daddy Avatar answered Oct 06 '22 13:10

P Daddy