Sergiy Belozorov
Sergiy Belozorov

Reputation: 6084

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.

Upvotes: 7

Views: 17889

Answers (2)

cdhowie
cdhowie

Reputation: 169328

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.

Upvotes: 7

Servy
Servy

Reputation: 203825

Have the method accept a Delegate, rather than a particular delegate:

void myFunction(Delegate func)
{

}

Upvotes: 0

Related Questions