Anonymous methods are another addition in the version 2.0 of C# programming language. The concept and application of anonymous methods is very similar to the anonymous classes in Java. During event handling, we used to write the code as
myButton.Click += new EventHandler(MyButton_OnClick);
public void MyButton_OnClick(object sender, EventArgs e)
{
// do something
}
Here we first added a delegate to myButton’s Click event. The delegate is made to reference the MyButton_OnClick() method which is defined earlier.
Anonymous methods allow you to define un-named methods on the fly as:
this.myButton.Click += delegate(object sender, EventArgs e) { MessageBox.Show("yes"); };
Notice that instead of passing the method name, we have defined the method with the ‘delegate’ keyword. Also note that we are specifying the exact signature of the method with its name replaced by the ‘delegate’ keyword. Finally note that the definition of our method ends with a semicolon ‘;’.
Anonymous methods can be useful when we only want to use our event handler to point to only one method. It can save code size and make it more readable if used appropriately. For example, in case of defining a new thread, now we don’t need to define a separate method and can write the application logic just after the thread is instantiated as in the following code
static void Main(string[] args) { Thread th = new Thread(delegate() { while (true) { Console.WriteLine("hello, world!"); } }); th.Start();
Thread.Sleep(100);
th.Abort();
Console.WriteLine(”Program finished”);
Console.ReadLine();
}
Here we defined the body of the method just with the Thread object instantiation. The Thread class requires a delegate of type ‘ThreadStart’ which requires a parameter-less method with no return type. We then started this new thread Execution and made out Main() method thread wait for 100 milliseconds after which it aborts the newly created thread execution and the program is finished.
When the program is executed, it continues to print ‘hello, world’ on console output for 100 milliseconds and then exits.
hello, world! hello, world! hello, world! hello, world! hello, world! hello, world! hello, world! hello, world! hello, world! hello, world! hello, world! Program finished