What is the difference between the 2 methods below ? They both return exactly the same (as far as I know) so i’m wondering why one would rather use the one over the other ?
Is there a specific case in which one of the 2 methods below would be preferable ?
Or are there any situations in which it would be better to use func<> over a normal method ?
private static int addThings(int x, int y)
{
return x*y;
}
private static Func<int,int,int> addMoreThings = (x,y) =>
{
return x*y;
};
Funcis a delegate – (what C++ programmers would call a strongly typed function pointer).The
Func<int,int,int>means a delegate for functions that take two integers and return an integer – any such function.In the case of
addThings, the calculation is done immediately and the result returned.In the case of
addMoreThings, the function is returned. It can be later invoked.It is difficult to recommend one over the other without more context – having the delegate version allows you to be lazy – to use the strategy pattern, for example by assigning the strategy to a delegate.