Purpose of lambda syntax in function/method

Asked

Viewed 159 times

5

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;
}

Meanwhile, to a new feature in C# 6.0 that allows declaring a function/method in lambda expression on only one line, see in the illustrative example:

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

And the way to call these functions and the same:

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

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

Exit:

Sum result = 15
Result of subtraction = 1

Dotnetfiddle complete of the example.


Doubts

This raised the following doubts:

  1. There is some limitation in a function/method in lambda syntax, if yes what?
  2. This function/method in lambda syntax can be called delegate?
  3. What is the purpose of this new feature?

1 answer

6


There is some limitation in a function/method in lambda syntax, if yes which?

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

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

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

What is the purpose of this new feature?

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

Further reading: Differences between readonly Func<> and method and What is the purpose of the operator => in the use of lists?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.