Kevin Dockx
Kevin Dockx

Reputation: 61

Pass method, created with reflection, as Func parameter

I've got a method (fyi, I'm using c#), accepting a parameter of type "Func", let's say it's defined as such:

MethodAcceptingFuncParam(Func<bool> thefunction);

I've defined the function to pass in as such:

public bool DoStuff()
{
    return true;
}

I can easily call this as such:

MethodAcceptingFuncParam(() =>  { return DoStuff(); });

This works as it should, so far so good.

Now, instead of passing in the DoStuff() method, I would like to create this method through reflection, and pass this in:

Type containingType = Type.GetType("Namespace.ClassContainingDoStuff");
MethodInfo mi = containingType.GetMethod("DoStuff");

=> this works, I can get the methodinfo correctly.

But this is where I'm stuck: I would now like to do something like

MethodAcceptingFuncParam(() => { return mi.??? });

In other words, I'd like to pass in the method I just got through reflection as the value for the Func param of the MethodAcceptingFuncParam method. Any clues on how to achieve this?

Upvotes: 6

Views: 2468

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500515

You can use Delegate.CreateDelegate, if the types are appropriate.

For example:

var func = (Func<bool>) Delegate.CreateDelegate(typeof(Func<bool>), mi);
MethodAcceptingFuncParam(func);

Note that if the function is executed a lot in MethodAcceptingFuncParam, this will be much faster than calling mi.Invoke and casting the result.

Upvotes: 11

Adrian Zanescu
Adrian Zanescu

Reputation: 8008

Use Invoke:

MethodAcceptingFuncParam(() => { return (bool)mi.Invoke(null, null); })

Upvotes: 1

Related Questions