Search code examples
c#genericsreflectiondelegatesmethod-signature

Delegate for any method type - C#


I want to have a class that will execute any external method, like this:

class CrazyClass
{
  //other stuff

  public AnyReturnType Execute(AnyKindOfMethod Method, object[] ParametersForMethod)
  {
    //more stuff
    return Method(ParametersForMethod) //or something like that
  }
}

Is this possible? Is there a delegate that takes any method signature?


Solution

  • You can do this a different way by Func<T> and closures:

    public T Execute<T>(Func<T> method)
    {
       // stuff
       return method();
    }
    

    The caller can then use closures to implement it:

    var result = yourClassInstance.Execute(() => SomeMethod(arg1, arg2, arg3));
    

    The advantage here is that you allow the compiler to do the hard work for you, and the method calls and return value are all type safe, provide intellisense, etc.