0

I am reading the book Functional Programming in C# by Enrico Buonanno (great book).

There is one example for swapping the order of arguments, namely:

static Func<T2, T1, R> 
     SwapArgs<T1, T2, R>(this Func<T1, T2, R> f) => (t2, t1) => f(t1, t2);

Can someone please explain why is the => used twice? For example, a function for diving would be written as

Func<int, int, int> divide = (x,y) => x / y;

The order is: function name followed by = followed by arguments followed by => followed by the function body. That is what is confusing me, in the SwapArgs we don't have = we have twice =>.


Could someone please clarify this?

NetMage
  • 26,163
  • 3
  • 34
  • 55
  • The first `=>` defines `SwapArgs` and could be replace with `{ return ` ... `; }` instead, so `static Func SwapArgs(this Func) { return (t2, t1) => f(t1, t2); }`. The second `=>` is shorthand for creating an anonymous method. – NetMage Jan 10 '23 at 22:23
  • It's worth noting that this is needlessly costly due to creating multiple method invocations (and an allocation for the closure) solely for the purpose of swapping argument order. I really wouldn't recommend doing something like this in real code. – David L Jan 10 '23 at 23:48
  • Thanks for the comment @NetMage! Also thanks @alexei-levenkov for redirecting me to the answers of my question. – Lazar Grbovic Jan 10 '23 at 23:49
  • 1
    @DavidL yes of course, this is for the demonstration purpose, as the author is explaining the higher-order functions. Thanks for the suggestion though! – Lazar Grbovic Jan 10 '23 at 23:50

0 Answers0