James
James

Reputation: 257

What are anonymous methods in C#?

Could someone explain what anonymous methods are in C# (in simplistic terms) and provide examples in possible please

Upvotes: 14

Views: 17748

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1499770

Anonymous methods were introduced into C# 2 as a way of creating delegate instances without having to write a separate method. They can capture local variables within the enclosing method, making them a form of closure.

An anonymous method looks something like:

delegate (int x) { return x * 2; }

and must be converted to a specific delegate type, e.g. via assignment:

Func<int, int> foo = delegate (int x) { return x * 2; };

... or subscribing an event handler:

button.Click += delegate (object sender, EventArgs e) {
    // React here
};

For more information, see:

Note that lamdba expressions in C# 3 have almost completely replaced anonymous methods (although they're still entirely valid of course). Anonymous methods and lambda expressions are collectively described as anonymous functions.

Upvotes: 24

Shadow Wizard
Shadow Wizard

Reputation: 66389

These are methods without name.

For example, ordinary method is:

public void Foo()
{
   Console.WriteLine("hello");
}

While anonymous method can be:

myList.ForEach(item => Console.WriteLine("Current item: " + item));

The code inside the ForEach is actually a method but has no name and you can't call it from the outside.

Upvotes: 5

Dariusz Tarczynski
Dariusz Tarczynski

Reputation: 16711

Anonymous method is method that simply doesn't have name and this method is declared in place, for example:

Button myButton = new Button();
myButton .Click +=
delegate
{
    MessageBox.Show("Hello from anonymous method!");
};

Upvotes: 10

Will A
Will A

Reputation: 24988

An anonymous method is a block of code that is used where a method would usually be required and which does not have a name (hence anonymous).

MSDN has examples of using anonymous methods.

Upvotes: 5

Related Questions