Easy Tutorial
❮ Csharp Constants Csharp Preprocessor Directives ❯

C# Anonymous Methods

We have mentioned that delegates are used to reference methods that have the same signature. In other words, you can call a method that can be referenced by the delegate using the delegate object.

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are methods without a name, only a body.

In anonymous methods, you do not need to specify the return type; it is inferred from the return statement within the method body.

Syntax for Writing Anonymous Methods

Anonymous methods are declared by creating an instance of a delegate using the delegate keyword. For example:

delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x)
{
    Console.WriteLine("Anonymous Method: {0}", x);
};

The code block Console.WriteLine("Anonymous Method: {0}", x); is the body of the anonymous method.

Delegates can be invoked using the anonymous method or by using a named method, i.e., by passing method parameters to the delegate object.

Note: The body of the anonymous method requires a ; at the end.

For example:

nc(10);

Example

The following example demonstrates the concept of anonymous methods:

using System;

delegate void NumberChanger(int n);
namespace DelegateAppl
{
    class TestDelegate
    {
        static int num = 10;
        public static void AddNum(int p)
        {
            num += p;
            Console.WriteLine("Named Method: {0}", num);
        }

        public static void MultNum(int q)
        {
            num *= q;
            Console.WriteLine("Named Method: {0}", num);
        }

        static void Main(string[] args)
        {
            // Creating a delegate instance using an anonymous method
            NumberChanger nc = delegate(int x)
            {
                Console.WriteLine("Anonymous Method: {0}", x);
            };

            // Invoking the delegate using the anonymous method
            nc(10);

            // Instantiating the delegate using a named method
            nc = new NumberChanger(AddNum);

            // Invoking the delegate using the named method
            nc(5);

            // Instantiating the delegate using another named method
            nc = new NumberChanger(MultNum);

            // Invoking the delegate using the named method
            nc(2);
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following result:

Anonymous Method: 10
Named Method: 15
Named Method: 30
❮ Csharp Constants Csharp Preprocessor Directives ❯