In C # 1.1, declaring and using a delegate requires that you have a delegate and an executable method that has a matching signature when the delegate is triggered, and an allocation statement that associates the named method with the delegate. As a new feature of C # 2.0, an anonymous method can basically provide the same functionality as a previous named method, but it no longer requires a method that is explicitly created before it is associated with a delegate.
You can imagine an anonymous method as a convenient way to implement the functionality associated with a delegate. If you look at the IL results obtained by the anonymous method implementation and the naming method implementation at the same time, you will find that the difference between the two is very small. When the compiler encounters an anonymous method, it creates a named method inside the class and associates it with the delegate. So anonymous methods are very similar to the performance of named methods during run time--performance increases are reflected in the productivity of the developer, not in the execution of the runtime.
How to use anonymous methods
It is easier to use more code to explain and understand anonymous methods less by preaching. The following example should illustrate how you can take advantage of anonymous methods:
Example 1--basic knowledge
Using anonymous methods is simple. You just have to put the anonymous method in the associated statement where you usually put the naming method. In the following example, I associate the anonymous method with the delegate for example 1:
Example List 1
#region Simple example - Example1
private delegate void Example1();
privatevoid btnExample1_Click(object sender, EventArgs e)
{
//Declare an instance of the Example1 delegate.
// You can see where I'm using the anonymous
// method in place of a named method - it follows
// the delegate() keyword.
Example1 example =
newExample1(
delegate()
{
MessageBox.Show("Example1");
});
example();
}
#endregion