What are anonymous methods and what is their main purpose?

Asked

Viewed 872 times

4

I know they’re used to working together with delegates, but the sources I found were a little confused in my opinion.

2 answers

5

It is a way to create a delegate as well as lambda expressions.

The C# along its evolution has been introducing new ways to create delegates, which practically makes the previous versions unused, almost unused I would say... is the case here.

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

In the microsoft website have examples about 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); };

The guy 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 advances a little more in the ways of defining a delegate, which is not in this Microsoft document (it is outdated by the visa).

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... left aside for anonymous methods and lambda expressions.

  • Local function has nothing to do with delegate or anonymous methods, or anything like that. It is the equivalent of a normal method only deprived of the method where it was declared, with some obvious limitations. I have already answered this at https://answall.com/q/181290/101

  • On the site itself it is said that anonymous functions are the set of anonymous methods + lambda expressions. I used the link as a reference to show the evolution of language and justify what I said about being outdated, that’s all. = D

  • Do you have reference to this? Because it is clearly wrong, it has nothing of expression lambda or anonymous method in local function, are very different mechanisms (on the surface or internally), with different commitments, with different objectives, the only thing in common is that they have parameters, code in the body and possible return.

  • I think you were referring to local functions... but still, they’re not just functions in the local scope. They can capture variables from the external scope (itself), and can later be stored in a delegate.

  • They cannot, they access variables of external scope because they are in the same scope, for all the effects it is as if it were a whileor a if or just { ... }, but without capture and if they are used in a closure is another totally distinct thing not associated with being a local function.

  • Since they cannot... place a local function inside a for. Use the iterator inside it, making a copy before, for another variable. And then you’ll see that the variable is captured.

  • Action<string> lista = null; for (var i = 0; i < 100; i++) { var i2 = i; void testDelD(string x) { Console.WriteLine(i2 + x); } lista += testDelD; } lista(" -&#xA; X");

  • From what I understand, local function is the syntactic definition of the resource. What the compiler or JITTER does behind it is disconnected. Just like when it comes to whether an object is in the stack or in the heap, based on whether it’s struct or class.

  • There was no capture in the local function, only accessed the variable that was in the current scope. The capture occurred in the anonymous method that delegates the execution to the local function. Without a delegate there is no way to do this. Unless we have different definitions of capture. Having access to the variable of the external scope for me is not capture, although I saw article using this term, but it is wrong, the capture depends on an infrastructure to load the variable to where you want and only one delegate has it.

  • And isn’t that what happened? She not only accessed the variable, but also copied the value and took it with her. The same would occur with a lambda attributed to a delegate. I think I understand what you mean... just as a lambda expression is neither delegate nor Expressiontree until it is used, a local function is nothing either until it is used. Beauty! ... however, the focus of my answer is on the evolution of ways to create delegates. To me, that seems to be a new way. Just like the way it was using lambda expressions when it first appeared.

  • It will soon solve what local functions can be used to create Expressiontrees. The question then is that all things are anything, just that the compiler gives support for such.

  • Local function is not an evolution of delegate, I’m not going to repeat what I’ve already said about this, so much so that you had to create both to get what you wanted. About the future I do not know, I know that today are different things, with different infrastructure to obtain final results and commitment of different processing and memory. But never mind, stay here the caveat that this is wrong, I’ve said what I had to say, will be repetitive.

Show 7 more comments

4


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

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

The delegate is just a syntax to define an anonymous method. But the delegate may have an associated name as well. The delegate in direct use is virtually obsolete in normal applications.

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

Today we use the syntax of lambda that is always anonymous.

(i) => WriteLine(i);

For example can do:

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

I put in the Github for future reference.

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, then the name is provisional, is linked to its support and not to the method.

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

Browser other questions tagged

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