Anonymous Methods

Anonymous methods are methods that are not actually defined, therefore, only suited for one-time use. Anonymous methods are targeted for delegates. The following shows the syntax of an anonymous method.

delegate (parameters)
{
    //Code for the anonymous method
};

For example, we can define a delegate, create an object of that delegate, and assign the anonymous method to it.

using System;

namespace AnonymousMethodsDemo
{
    public delegate void MessageDelegate(string message);

    public class Program
    {
        public static void Main()
        {
            MessageDelegate ShowMessage = new MessageDelegate(
            delegate(string message)        
            {                               
                Console.WriteLine(message); 
            }                               
            );                              

            ShowMessage("Hello World!");
        }
    }
}

Example 1 – Anonymous Method Demo

 Hello World

Here, the delegate has a return type of void, and one string parameter. When we created our delegate object, we passed an anonymous method to it. Notice that the anonymous method has also a string parameter to match its delegate. The return type is automatically detected. If no return statement was found, then it will have a return type of void. If your delegate has a return type, then your anonymous method should have a return statement returning the proper type of value. You can even simplify the code above like this:

MessageDelegate ShowMessage = delegate(string message)
                              {
                                  Console.WriteLine(message);
                              };

Anonymous methods can also be used when subscribing to events.

myClass.myEvent += delegate(string message)
                   {
                       Console.WriteLine(message);
                   };