-1

I am quite new in C# and my professor gave me this code, can you explain how does it work? I am curious about all these "=>" operators, and what is going on in Dictionary.

            _operationFunction = new Dictionary<string, Func<int, int, int>>
            {
                ["+"] = (fst, snd) => (fst + snd),
                ["-"] = (fst, snd) => (fst - snd),
                ["*"] = (fst, snd) => (fst * snd),
                ["/"] = (fst, snd) => (fst / snd)
            };
           _operators.Push(_operationFunction[op](num1, num2));

        Func<int, int, int> Operation(String input) => (x, y) =>
            (
                (input.Equals("+") ? x + y :
                    (input.Equals("*") ? x * y : int.MinValue)
                )
            );
        _operators.Push(Operation(op)(num1, num2));
Dairon
  • 13
  • 1
  • 1
    See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator – Terry Tyson Oct 28 '20 at 20:03
  • 1
    The `["+"]` defines a key value, and the part after the `=` is shorthand for a function that takes in two integers (`fst` and `snd`) and returns a third integer (`(fst + snd)`). So it's assigning an "add" function to the "+" key of the dictionary. – Rufus L Oct 28 '20 at 20:06

1 Answers1

0

This (as well as the other expressions, with => )

(fst, snd) => (fst + snd)

is a lambda expression.

The lambda expressions in the dictionary represent the arithmetical operations between integers. So for each of the four operations of addition (+), multiplication (*), subtraction (-) and division (/), a lambda expression is supplied that describes these operations.

When we write the following:

_operationFunction[op](num1, num2)

the value of the dictionary associated with the key op is fetched and then the returned function (value) is applied for the integers num1 and num2.

So if the value of op is the string "+", then _operationFunction[op] returns a reference to the delegate essentially that is described by the lambda expression:

(fst, snd) => (fst + snd)

Then the "function" that this reference points to is applied for the arguments num1 and num2.

You can read at Func<T1,T2,TResult> more regrading this that is used in your code.

Christos
  • 53,228
  • 8
  • 76
  • 108