-1

Let us suppose that I have two functions like:

public T Foo<T>(Func<T> func){
    return func();
}

public TResult Foo<T, TResult>(Func<T, TResult> func, T param){
    return func(param);
}

And I have the following code to execute:

someObj.someMethod(someParam);

Which approach is preferable, and what is the difference?

var foo = Foo(() => someObj.someMethod(someParam));

or

var foo = Foo(someObj.someMethod, someParam);
Andre
  • 652
  • 2
  • 7
  • 23
  • Those are different function signature what's your question? – D-Shih Dec 09 '18 at 10:27
  • That entirely depends on the purpose. In your example, why do you need `Foo` at all, if all it does is apply the function? – JimmyMcHoover Dec 09 '18 at 10:28
  • @D-Shih I have this code to execute as delegate someObj.someMethod(someParam); and I have these two options, and it`s not clear which one is preferable and why – Andre Dec 09 '18 at 10:28
  • @Ragnagord Its just a example, Internally I`m logging stuff – Andre Dec 09 '18 at 10:29

2 Answers2

1

1st approach seems to be more preferable.

Foo(() => someObj.someMethod(someParam));

As someParam is related to someMethod more than Foo.

amanmehara
  • 134
  • 1
  • 8
1

Since there are no context as to why you would like to use one over the other I will cover differences.

From closure point of view it will behave in the same way (unless 2nd method performs transformations or capturing of passed value). Variable is not capture thus executing method with this value (assuming it is mutable) might yield different results. Another difference is that you create another method vs just passing existing method reference.

In general, you prefer to use second approach if you wish to use passed value in some way. I.e. you have a try/catch wrapper, so you would like to print value in case of failure. Otherwise just go with first one.

Karolis Kajenas
  • 1,523
  • 1
  • 15
  • 23
  • In fact I change the code in example to capture the return.. Anyway what do you mean by:Variable is not capture thus executing method with this value (assuming it is mutable) might yield different results, I think Its just matter if a capture the return not? Sorry if I misunderstood what you mean – Andre Dec 09 '18 at 11:11
  • @Andre It might yield different results if your variable is changed after initial creation of the method. So it will execute this func with different variable than it was created with. Since most likely variable you're passing is reference type. – Karolis Kajenas Dec 09 '18 at 11:56