C# anonymous methods

In C#, anonymous methods are a feature that allows you to define a method without explicitly naming it. Anonymous methods are often used in event handlers, where you need to define a method to be called when an event is triggered, but you don't want to define a separate method for each event.

To define an anonymous method, you use the delegate keyword and the delegate() syntax to define the method's signature. You then provide the method body as a code block. Here's an example:

‮ refer‬to:theitroad.com
button1.Click += delegate(object sender, EventArgs e)
{
    MessageBox.Show("Button clicked!");
};

In this example, we attach an anonymous method to the Click event of a button. The anonymous method takes two parameters, an object representing the sender of the event, and an EventArgs object representing the event arguments. The body of the method is a code block that shows a message box.

You can also use anonymous methods to define local methods inside other methods. Here's an example:

public void DoSomething()
{
    int x = 10;

    // Define an anonymous method
    Action<int> print = delegate(int value)
    {
        Console.WriteLine(value);
    };

    print(x);
}

In this example, we define an anonymous method inside the DoSomething() method that takes an integer parameter and writes it to the console. We then create a delegate of type Action<int> and assign the anonymous method to it. Finally, we call the delegate with the value of x.

Anonymous methods are similar to lambda expressions in C#, which were introduced in C# 3.0. However, lambda expressions provide a more concise syntax for defining inline methods, and they support closures, which allow them to access variables from the enclosing scope.