Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an arbitrary method (or delegate) as parameter to a function?

I need to be able to pass an arbitrary method to some function myFunction:

void myFunction(AnyFunc func) { ... }

It should be possible to execute it with other static, instance, public or private methods or even delegates:

myFunction(SomeClass.PublicStaticMethod);
myFunction(SomeObject.PrivateInstanceMethod);
myFunction(delegate(int x) { return 5*x; });

Passed method may have any number of parameters and any return type. It should also be possible to learn the actual number of parameters and their types in myFunction via reflection. What would be AnyFunc in the myFunction definition to accommodate such requirements? It is acceptible to have several overloaded versions of the myFunction.

like image 570
Sergiy Belozorov Avatar asked Apr 10 '13 16:04

Sergiy Belozorov


People also ask

Can we pass delegate as parameter?

Because the instantiated delegate is an object, it can be passed as an argument, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time.

Can we pass method as parameter in C#?

In C#, we can also pass a method as a parameter to a different method using a delegate. We use the delegate keyword to define a delegate. Here, Name is the name of the delegate and it is taking parameter. Suppose we have a delegate having int as the parameter.

How to use delegate function in C#?

A delegate can be declared using the delegate keyword followed by a function signature, as shown below. The following declares a delegate named MyDelegate . public delegate void MyDelegate(string msg); Above, we have declared a delegate MyDelegate with a void return type and a string parameter.

What is delegate in. net explain with an example?

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.


1 Answers

The Delegate type is the supertype of all other delegate types:

void myFunction(Delegate func) { ... }

Then, func.Method will give you a MethodInfo object you can use to inspect the return type and parameter types.

When calling the function you will have to explicitly specify which type of delegate you want to create:

myFunction((Func<int, int>) delegate (int x) { return 5 * x; });

Some idea of what you're trying to accomplish at a higher level would be good, as this approach may not turn out to be ideal.

like image 195
cdhowie Avatar answered Nov 22 '22 14:11

cdhowie