Introduction
Anonymous Methods are a new feature of C# v2.0. Anonymous Methods are similar to delegates in C#, but require less code. A method without a name is called an anonymous method. An anonymous method is different from regular methods. This method is not declared as a simple method or regular method.
- Benefits of anonymous methods
- Implement an anonymous method
- Implement anonymous methods that use delegate parameters
Benefits of Anonymous Methods
Anonymous methods are used to define delegates and to write inline functions. The benefit of anonymous methods is, improve development experience over using delegates. The main benefits of anonymous methods is to implement delegates with less code.
Implementing an Anonymous Method
An anonymous method uses the keyword, delegate,
instead of a method name. This is followed by the body of the method. Typical
usage of an anonymous method is to assign it to an event.
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;
namespace
Anonymous_Method
{
public partial
class Form1
: Form
{
public Form1()
{
InitializeComponent();
Button btnHello =
new Button();
btnHello.Text = "Hello";
btnHello.Click +=
delegate
{
MessageBox.Show("Hello
Vineet...");
};
Controls.Add(btnHello);
}
private void
Form1_Load(object sender,
EventArgs e)
{
}
}
}
Code Description
The code shown above instantiates a Button control and sets its text to "Hello". This code uses an anonymous method inside of a method, but the body of the anonymous method doesn't execute with the rest of the code. When you run the program and click the Hello button, you will see a message box i.e. "Hello Vineet.." . The Controls.Add, adds the new button control to the window. You can say that the preceding program uses an anonymous method because it uses the delegate keyword.



Mariusz PostolPosted Oct 2, 2025, 7:43 PM
Func<int, int, int> add = (a, b) => a + b; => a+b is a return statement, isn't it? It is not an expression but rather a simplified return instruction where the return keyword has been neglected, but can be added. If you are interested more you can check out the video at <https://youtu.be/6A0riw8Zm0Q>