Anonymous methods in C# are a unique way of defining unnamed inline methods, which are ideal when you need a short, single-use function. Introduced in C# 2.0, anonymous methods are often used with delegates and provide a more compact, flexible way of handling specific scenarios where a fully declared method might be excessive. This guide covers anonymous methods in-depth, including syntax, use cases, examples, and real-world applications.
In C#, an anonymous method is essentially a block of code that you define inline, directly in the place where it is needed, without assigning it a name. This approach is particularly useful for defining short functions that are only intended for a specific use, such as event handling, small calculations, or delegates that will only be invoked in a specific context.
Anonymous methods are frequently used with:
delegate
implementations.An anonymous method is defined using the delegate
keyword, followed by the parameter list in parentheses and a code block within curly braces { }
.
delegate (parameters)
{
// Method body
};
delegate
{
Console.WriteLine("Hello from an anonymous method!");
};
delegate (int a, int b)
{
return a + b;
};
Here’s an example where an anonymous method is assigned to a delegate and then invoked.
using System;
delegate void GreetDelegate(string name);
class Program
{
static void Main()
{
GreetDelegate greet = delegate (string name)
{
Console.WriteLine($"Hello, {name}!");
};
greet("Alice"); // Output: Hello, Alice!
}
}
GreetDelegate
is a delegate that takes a string parameter.greet
, which prints a greeting message.In this example, we use an anonymous method to perform a calculation within a delegate
.
using System;
delegate int CalculateDelegate(int x, int y);
class Program
{
static void Main()
{
CalculateDelegate add = delegate (int x, int y)
{
return x + y;
};
int result = add(5, 10);
Console.WriteLine(result); // Output: 15
}
}
CalculateDelegate
takes two integers and returns an integer.List<T>.ForEach
Anonymous methods are useful for list operations, such as printing each element in a list.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
names.ForEach(delegate (string name)
{
Console.WriteLine(name);
});
}
}
ForEach
iterates through each element in the names list.In GUI applications (e.g., WinForms or WPF), anonymous methods simplify event handling, especially for small or one-time event handlers. Here’s an example of how an anonymous method can be used to handle a button click event in a Windows Forms application.
using System;
using System.Windows.Forms;
public class MyForm : Form
{
private Button clickButton;
public MyForm()
{
clickButton = new Button();
clickButton.Text = "Click Me";
clickButton.Location = new System.Drawing.Point(50, 50);
// Using an anonymous method for the button's Click event
clickButton.Click += delegate (object sender, EventArgs e)
{
MessageBox.Show("Button clicked!");
};
Controls.Add(clickButton);
}
[STAThread]
public static void Main()
{
Application.Run(new MyForm());
}
}
clickButton.Click
event is assigned an anonymous method to display a message box when the button is clicked.Real-World Use Case: Anonymous methods are commonly used in UI applications for temporary event handlers. For instance, if you want to handle button clicks, menu selections, or other UI events with a short, one-time action, using anonymous methods makes your code cleaner and more readable.
Anonymous methods in C# provide an efficient, inline approach for defining single-use methods, especially for event handling or delegate-based operations. They enhance code readability and reduce the need for additional methods, particularly when the functionality is brief or limited to a specific scope. While lambda expressions have largely replaced anonymous methods in modern C# development, understanding anonymous methods is essential for working with legacy code or specific cases where inline methods simplify code structure.