C# Anonymous method

In C#, an anonymous function is a method without a name that can be defined and used in code.

We have already mentioned that a delegate is used to reference methods with the same signature as itself. In other words, you can use a delegate object to call methods that can be referenced by the delegate.

Anonymous methodsIt provides a technique for passing code blocks as delegate parameters.

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

Lambda expression

Lambda expressions are a concise syntax for creating anonymous functions. They are commonly used in LINQ queries and delegates.

Syntax

(parameters) => expression
// 或
(parameters) => { statement; }

Example

// Example: Using a Lambda expression to define a delegate
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(2, 3)); // output 5

// Example: Use Lambda expressions to filter elements in an array
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var num in evenNumbers)
{
    Console.WriteLine(num); // Output 2 4
}

Anonymous method

Anonymous methods are created by usingdelegateis declared by using the keyword to create a delegate instance.

Syntax

delegate(parameters) { statement; }

For example:

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 body of the anonymous method.

A delegate can be invoked through an anonymous method or a named method, that is, by passing a method argument to the delegate object.

Note:The body of the anonymous method is followed by a;。

For example:

nc(10);

Example

// Example: Using an anonymous method to define a delegate
Func<int, int, int> multiply = delegate (int a, int b)
{
    return a * b;
};
Console.WriteLine(multiply(2, 3)); // Output 6

// Example: Using an anonymous method as an event handler
Button button = new Button();
button.Click += delegate (object sender, EventArgs e)
{
    Console.WriteLine("Button clicked!");
};

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)
        {
            // Create a delegate instance using an anonymous method
            NumberChanger nc = delegate(int x)
            {
               Console.WriteLine("Anonymous Method: {0}", x);
            };
           
            // Call the delegate using an anonymous method
            nc(10);

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

            // Instantiate a delegate using another named method
            nc =  new NumberChanger(MultNum);
           
            // Call the delegate using a named method
            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

In C# 2.0 and later versions, lambda expressions were introduced, which are a more concise syntax for writing anonymous methods.

Using lambda expressions:

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)
        {
            // Create a delegate instance using a lambda expression
            NumberChanger nc = x => Console.WriteLine($"Lambda Expression: {x}");

            // Using a lambda expression to invoke a delegate
            nc(10);

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

            // Call the delegate using a named method
            nc(5);

            // Instantiate a delegate using another named method
            nc = new NumberChanger(MultNum);

            // Call the delegate using a named method
            nc(2);

            Console.ReadKey();
        }
    }
}
other extensions