Given this example code:
enum op
{
add,
remove
}
Func<op, int> combo(string head, double tail) =>
(op op) =>
op == op.add ? Int32.Parse(head) + Convert.ToInt32(tail) : Int32.Parse(head) - Convert.ToInt32(tail);
Console.WriteLine(combo("1", 2.5)(op.remove));
Which returns:
-1
What does the first arrow operator mean?
By specification it does not look like an expression body or a lambda operator.
Is there any reference in the C# language specification about this usage?
In newer versions of C#, you are allowed to write:
as the shorter and clearer:
It is nothing more than a "syntactic sugar" that lets you write a simple method in a shorter and more direct way.
The left
=>indicates an expression body. The right=>indicates a lambda. So it is somewhat confusing in your example because the thing being returned is a lambda, which also uses=>. But do not let that distract you:is just a short way of writing
Which in turn is just a short way or writing
If you find code with multiple
=>operators confusing you can always remove them by desugaring them into the more explicit form. It's just a short form that some people find easier to read.Sure. Here are two equivalent ways to write that code.
Sure; that is a little more complicated. We will do it in a series of small steps:
We start with this:
Desugar the outer function:
Turn the inner function into a helper:
Now move the helper method to a class:
Now make head and tail members of closure:
And now we can desugar the lambda:
And we're done.
If you decompile your code using ILDASM or sharplab.io or some such tool you will discover that this is exactly what the compiler generates for your code, except that it generates weird, illegal names for the helpers to ensure that you never accidentally call one of them by mistake.