Anonymous methods in C# provide a convenient way to create inline methods without having to declare a separate method. They are often used with delegates, especially when passing a short piece of code to a method.
The syntax for an anonymous method is:
delegate (parameter_list) {
// method body
}
The delegate keyword is used to introduce an anonymous method. The parameter_list is optional and defines the parameters the anonymous method accepts, similar to a regular method.
Anonymous methods are frequently used to instantiate delegates inline. Consider the following example:
using System;
public delegate void MyDelegate(string message);
public class Program
{
public static void Main(string[] args)
{
// Using an anonymous method to instantiate MyDelegate
MyDelegate del = delegate(string msg)
{
Console.WriteLine("Anonymous method says: " + msg);
};
del("Hello from anonymous method!");
}
}
Output:
Anonymous method says: Hello from anonymous method!
Anonymous methods can capture variables from their enclosing scope. This means they can access and modify local variables defined outside of the anonymous method.
using System;
public delegate void NumberChangerDelegate(int n);
public class Program
{
static int num = 10;
public static void Main(string[] args)
{
// Anonymous method capturing 'num'
NumberChangerDelegate changer = delegate(int n)
{
num = num + n;
Console.WriteLine("The new value of num is: " + num);
};
changer(5); // num becomes 15
changer(2); // num becomes 17
}
}
Output:
The new value of num is: 15
The new value of num is: 17
Lambda expressions, introduced in C# 3.0, are a more concise syntax for creating inline delegate instances and are generally preferred over anonymous methods for their brevity and expressiveness. However, anonymous methods offer backward compatibility and some distinct features, particularly in how they handle the ref and out keywords (which lambda expressions do not support directly when capturing).
A lambda expression equivalent to the first example would be:
MyDelegate del = (string msg) => Console.WriteLine("Anonymous method says: " + msg);
And the second example:
NumberChangerDelegate changer = (int n) => {
num = num + n;
Console.WriteLine("The new value of num is: " + num);
};
For more advanced scenarios or when dealing with asynchronous operations, consider exploring async/await patterns.
↑