What are anonymous methods and what is their main purpose?

3

I know they're used to working with delegates , but the sources I found were a bit confusing in my opinion.

    
asked by anonymous 04.10.2017 / 03:17

2 answers

3

Anonymous method is an unnamed method, it is a method that does not have a symbol associated with it at compile time.

You only have one reference to the code and this reference can be assigned to a variable of any type, passed as an argument to another method, or returned from a method.

The delegate is just a syntax for defining an anonymous method. But the delegate may have an associated name too. The direct-use delegate is practically obsolete in normal applications.

delegate(string i) { WriteLine(i); };

Today, the lambda syntax is always anonymous.

(i) => WriteLine(i);

For example you can do:

public Action<string> Metodo() {
    Action<string> func = (i) => WriteLine(i);
    func("teste"); //imprime teste
    return func;
}

In this way the method has no name, but the variable that supports it has. Obviously at the moment the anonymous method returns it will probably be assigned to another variable, so the name is temporary, it is linked to its support, not to the method.

More details on What's the difference between a lambda expression, a closure, and a delegate? .

    
04.10.2017 / 03:30
3

This is a way to create a delegate, as well as lambda expressions.

C # throughout its evolution has been introducing new ways to create delegates, which virtually makes the previous versions little used, almost unusable I would say ... this is the case here.

An anonymous method is called so, because it is not referable via a static name (I mean, a compile-time name, statically parsable = D).

In the Microsoft website examples of this evolution.

C # 1:

// Sintaxe original de delegate requer a
// inicialização com um método nomeado.
TestDelegate testDelA = new TestDelegate(M);

The M above is a named method:

static void M(string s)
{
    Console.WriteLine(s);
}

// Chamando o delegate.
testDelA("Delegate criado com argumento, usando um Method Group.");

C # 2:

// C# 2.0: Um delegate pode ser inicializado com
// código inline, chamado da "método anônimo."
// Nesse formato, o tipo dos argumentos é explícito.
// Note que o método não possui um nome.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

C # 3:

// C# 3.0. O delegate pode ser inicializado a partir
// de uma expressão lambda. Neste caso, já se evoluiu para haver
// inferência de tipos. O tipo de 'x' é inferido a partir do
// tipo de delegate TestDelegate.
TestDelegate testDelC = (x) => { Console.WriteLine(x); };

Type TestDelegate :

delegate void TestDelegate(string s);

testDelB("That's nothing. I'm anonymous and ");
testDelC("I'm a famous author.");
testDelD("I'm a famous author.");

C # 7:

And now C # 7 has local functions, which goes a little further on how to define a delegate, which is not in this Microsoft document (it's out of date).

static void Main(string[] args)
{
    testDelD(Exemplo usando função local.");

    void testDelD(string x) { Console.WriteLine(x); }
}

The interesting thing is that local functions bring back the names ... set aside for anonymous methods and lambda expressions.

    
04.10.2017 / 03:29