Purpose of the lambda syntax in function / method

4

In some cases a function / method contains only one line in its scope, see the illustrative example:

static int Soma(int a, int b)
{
    return a + b;
}

However, the new feature in C # 6.0 which allows declaring a function / method in lambda expression in just one line, see the illustrative example:

static int Subtrai(int a, int b) => a - b;

And the way to call these functions is the same:

var resultadoSoma = Soma(10, 5);
var resultadoSubtracao = Subtrai(10, 9);

WriteLine($"Resultado da soma = {resultadoSoma}\nResultado da subtração = {resultadoSubtracao}");

Output:

  

Result of sum = 15
  Subtraction result = 1

Dotnetfiddle full of the example.

Questions

This gave me the following doubts:

  • Is there any limitation on a function / method in lambda syntax, if yes which ones?
  • This function / method in lambda syntax can be called delegate?
  • What is the purpose of this new feature?
  • asked by anonymous 22.07.2016 / 19:31

    1 answer

    5
      

    Is there any limitation on a function / method in lambda syntax, if so which ones?

    Just that it can only be a line with an expression that is your return. Even C # 6 could not be used in any method. Now even builders, destructors, and property accessors can use.

      

    This function / method in lambda syntax can be called a delegate?

    No, it is a normal function, only the syntax is similar to lambda , it does not have the same characteristics as an anonymous function. The semantics is of "pure" function.

      

    What is the purpose of this new feature?

    Make the code shorter and more enjoyable to read, nothing more.

    Further reading: Differences between readonly Func

    22.07.2016 / 19:46