Search code examples
c#nlogmethod-parametersswallowed-exceptions

How to pass a reference to a STATIC method as a function parameter in C#?


I need to use a Swallow(Func) method from NLog library. Important note: I call Swallow from a static method and want to pass a static method.

Its documentation is here:

http://nlog-project.org/documentation/v3.2.1/html/Overload_NLog_Logger_Swallow.htm

The first case (Swallow(Action)) (passing static methods WO parameters) works straightforward:

static void ParameterlessMethodThatCasts ()
{
   throw NotImplementedException("Not implemented yet");
}

...
// Code in some method that uses static instance of nLog
nLog.Instance.Swallow( ParameterlessMethodThatCasts );

Unfortunately, there is no example provided for the 2nd (Swallow<T>(Func<T>)) and 3rd (Swallow<T>(Func<T>, T)) overload, in which both cases are passed method references with parameters.

I did not find appropriate example elsewhere either.

I have tried myself:

`Object.TypeOf()` 

and var t = typeof(MyMethod);

Neither of them are syntactically correct.

What syntax should I use here instead, to pass a ref to a method with parameters (i.e. the second and third overload in the link above.) ?

Is there other way than passing a delegate ?


Solution

  • You could pass in a Func<T> or Func<T, T> if you will, but maybe it is more suitable for you to pass in an anonymous lambda expression:

    () => this.ParameterlessMethodThatCasts("A", "B", 1, 2)
    

    Since this signature matched the first overload, you can pass in any parameters you want.

    The Func<T> and Func<T, T> would match a method like this (where T is string in this case):

    private string SomeMethod(); // Func<T>
    

    And this:

    private string SomeMethod(string arg1); // Func<T, T>