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

Asked

Viewed 203 times

5

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

1 answer

5


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

One another question maybe it helps to understand what function is a thing and lambda is another, even if the syntax may be similar.

A local function cannot be confused with a delegated function because there is no indirect extra on her.

The local function for all purposes is a function like any other, but has a local scope to the function where it was defined. No one can call this function local except the function containing it.

The local function does not leave from within where it was created, unlike a lambda that can have its lifetime extended by returning a reference to it, or even by placing a reference on some object that has lifespan greater than the function.

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

The local function does not add anything revolutionary in the language, it only allows some code to be encapsulated. 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 kind. The local function internalizes it in only one function that can call it. It has always been possible to live without it, but now we can organize it 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 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

I put in the Github for future reference.

Then we conclude that they are things that have no relationship.

Browser other questions tagged

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