C# anonymous method


Release date:2023-09-07 Update date:2023-10-13 Editor:admin View counts:182

Label:

C# anonymous method

We have already mentioned that delegates are used to reference methods that have the same label as them. In other words, you can use a delegate object to call a method that can be referenced by a delegate.

Anonymous methods provide a technique for passing code blocks as delegate parameters. An anonymous method is a method that has no name but only a principal.

You do not need to specify a return type in an anonymous method, it is derived from the return statement inferred.

Write the syntax for anonymous methods

Anonymous methods are done by using the delegate keyword to create a delegate instance to declare. For example:

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

Code block Console.WriteLine("Anonymous Method: {0}", x); is the bodyof an anonymous method.

A delegate can be called either through an anonymous method or through a named method call, that is, by passing method parameters to the delegate object.

Note: the body of an anonymous method needs a ; .

For example:

nc(10);

Example

The following example demonstrates the concept of anonymous methods:

Example

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 anonymous methods
            NumberChanger nc = delegate(int x)
            {
               Console.WriteLine("Anonymous Method: {0}", x);
            };

            // Using anonymous methods to call delegates
            nc(10);

            // Instantiating delegates using naming methods
            nc =  new NumberChanger(AddNum);

            // Calling delegates using named methods
            nc(5);

            // Instantiating a delegate using another naming method
            nc =  new NumberChanger(MultNum);

            // Calling delegates using named methods
            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

Powered by TorCMS (https://github.com/bukun/TorCMS).