What are the differences between local functions, delegates and lambdas expressions?

4

Local functions will be present in C # 7. Given this, I would like to know the main differences between local functions , delegates and expressions lambdas .

    
asked by anonymous 01.02.2017 / 02:20

1 answer

4

The difference between delegate and lambda has already been answered in another question .

A another question might help you understand which function is one thing and lambda is other, even though the syntax may look similar.

A local function can not be confused with a delegated function because there is no extra indirection in it.

The local function for all effects is a function like any other, but has a local scope to the function where it was defined. No one can call this local function other than the function that contains it.

The local function does not go out from where it was created, unlike a lambda that can have its extended lifetime returning a reference to it, or even putting a reference in some object that has longer life than the function.

I have already given an answer giving an example of a local function and how it is different from a lambda .

The local function does not add anything revolutionary to the language, it only allows you to encapsulate some code a bit. Before you could protect a function not to be accessed from outside its type (classes, structure, etc.). But even a private function could be called by any function of that type. The local function internalizes it into only one function that can call it. You could always live without it, but now we can organize better.

Example:

static void mostraNome(string nome) {
    string transformaMaiuscula(string str) { //não pode ser chamada fora de mostraNome
        return str.ToUpper();
    }
    Console.WriteLine(transformaMaiuscula(nome));
}

Or in simplified syntax:

static void mostraNome(string nome) {
    string transformaMaiuscula(string str) => str.ToUpper(); //isto não é lambda
    Console.WriteLine(transformaMaiuscula(nome));
}

If it were a lambda it would be quite different:

static Func<string, string> mostraNome(string nome) {
    Func<string, string> transformaMaiuscula = (string str) => str.ToUpper();
    Console.WriteLine(transformaMaiuscula(nome));
    return transformaMaiuscula; //poderá executar a lambda fora daqui
}

Then you can do this:

Func<string, string> funcao = mostraNome("João");
string maiusculo = funcao("José"); //está chamando a lambda

Then we conclude that these are things that have no relation at all.

    
01.02.2017 / 02:56