Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are anonymous methods in C#?

Tags:

c#

.net

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

like image 708
James Avatar asked May 15 '11 11:05

James


People also ask

What are anonymous methods?

Anonymous method is a block of code, which is used as a parameter for the delegate. An anonymous method can be used anywhere. A delegate is used and is defined in line, without a method name with the optional parameters and a method body. The scope of the parameters of an anonymous method is the anonymous-method-block.

What are anonymous methods and objects example?

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.

Why do we need anonymous method?

An anonymous method is a method which doesn't contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods.

What is anonymous type of functions?

Definition. Anonymous type, as the name suggests is a type that doesn't have any name. Anonymous types are the new concept in C#3.0 that allow us to create new type without defining them. This is a way to define read only properties into a single object without having to define type explicitly.


2 Answers

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:

  • My article (written a long time ago) on delegate changes in C# 2
  • MSDN on anonymous methods
  • Chapter 5 of C# in Depth if you fancy buying my book :)

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.

like image 104
Jon Skeet Avatar answered Oct 11 '22 01:10

Jon Skeet


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!");
};
like image 31
Dariusz Avatar answered Oct 11 '22 03:10

Dariusz