Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Any function as parameter

Tags:

c#

Is it possible to created a method that takes ANY method (regardless of it's parameters) as a parameter? The method would also have a params parameter which then takes all the parameters for the parameter-method.

So basically what I want is something like this:

public void CallTheMethod(Action<int> theMethod, params object[] parameters)

But then for any method, not just for methods that takes an int.

Is something like this possible?

Thanks

like image 300
The Oddler Avatar asked Aug 20 '13 14:08

The Oddler


3 Answers

Yes, with a delegate:

public object CallTheMethod(Delegate theMethod, params object[] parameters)
{
    return theMethod.DynamicInvoke(parameters);
}

But see Marc Gravell's comment on your question :)

Well, you could pass the non-specific Delegate, but DynamicInvoke is sloooooowwwwww (relatively speaking)

like image 56
Matten Avatar answered Oct 12 '22 10:10

Matten


It's possible, but not what should be done.

This is what I would do:

public void CallTheMethod(Action toCall)

You might go "huh". Basically, what it lets the user do is this:

CallTheMethod(() => SomeOtherMethod(with, some, other, parameters));

However, if you want it to return a type, it involves generics:

public void CallTheMethod<T>(Func<T> theMethod)

You can put generic constraints on that type, do whatever you want with it, etc.

like image 33
It'sNotALie. Avatar answered Oct 12 '22 09:10

It'sNotALie.


Yes. You can use DynamicInvoke to call the methods:

Action<int> method1 = i => { };
Func<bool, string> method2 = b => "Hello";

int arg1 = 3;
bool arg2 = true;
//return type is void, so result = null;
object result = method1.DynamicInvoke(arg1);

//result now becomes "Hello";
result = method2.DynamicInvoke(arg2);

A method to do this would become:

object InvokeMyMethod(Delegate method, params object[] args)
{
    return method.DynamicInvoke(args);
}
like image 3
Bas Avatar answered Oct 12 '22 09:10

Bas