Latest web development tutorials

C # anonymous method

We have already mentioned, is a delegate method having the same label for reference. In other words, you can use the delegate object can be referenced by the delegate method calls.

Anonymous method (Anonymous methods) to provide a pass code block as a delegate parameter technology.Anonymous method is not only the name of the main method.

In the anonymous method, you do not need to specify a return type, it is the return statement inside the method body inferred.

Write anonymous method syntax

Anonymous methods by creating delegate instance keyword to declare adelegate.E.g:

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

Code blockConsole.WriteLine ( "Anonymous Method: {0}", x); is the subject of anonymous methods.

Delegate can be invoked by an anonymous method to be invoked by naming method, namely, by passing parameters to the delegate object method.

E.g:

nc (10);

Examples

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);
        }
        public static int getNum ()
        {
            return num;
        }

        static void Main (string [] args)
        {
            // Use anonymous methods to create delegate instances NumberChanger nc = delegate (int x)
            {
               Console.WriteLine ( "Anonymous Method: {0}", x);
            };
            
            // Method call using anonymous delegate nc (10);

            // Use a named method to instantiate delegate nc = new NumberChanger (AddNum);
            
            // Using named delegate the method invocation nc (5);

            // Using another naming method to instantiate delegate nc = new NumberChanger (MultNum);
            
            // Using named delegate the method invocation nc (2);
            Console.ReadKey ();
        }
    }
}

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

Anonymous Method: 10
Named Method: 15
Named Method: 30