3

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 ?

Sold Out
  • 1,321
  • 14
  • 34
  • May be I will have to create a delegate and pass that, as suggested in this thread: http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp?rq=1 – Sold Out Jun 27 '16 at 10:41

1 Answers1

2

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>
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Patrick: Thanx for tip. I forgot to specify, that it was a static method environment where I do it. I have fixed it in the question. – Sold Out Jun 27 '16 at 10:40
  • So how does that change my answer? – Patrick Hofman Jun 27 '16 at 10:41
  • Patrick You are right ! I removed the type specification Swallow and it compiles now. Seems like its exactly what I want :) Let me check. – Sold Out Jun 27 '16 at 10:46
  • Okay. Nice! @Peter – Patrick Hofman Jun 27 '16 at 10:47
  • Patrick: Thank you again! You just taught me how do I create an ad-hoc delegate for a local use and pass as an argument :) I wonder, if that increases instruction cycle consumption versus that option, where I create a static delegate and pass always that one. – Sold Out Jun 27 '16 at 11:06