Member-only story
Anonymous Method in C# with Examples
3 min readJul 6, 2024
An anonymous method is a method which doesn’t contain any name which is introduced in C# 2.0. In C#, an anonymous method allows you to define a method inline without explicitly declaring a separate named method. It’s particularly useful when you need a method as a delegate parameter, such as for event handling or LINQ queries.
Here’s a basic syntax of an anonymous method:
Here’s how you declare and use interfaces in C#.
Example
// An Anonymous Method
delegate(parameters) {
// method body
};
For example, to create an anonymous method that wrapped a fruit name and assign it to a delegate:
Example
using System;
// Define a delegate
delegate void fruitName(string name);
public class Program
{
public static void Main(string[] arge)
{
// Create an anonymous method and assign it to a delegate
fruitName fruit = delegate(string name)
{
Console.WriteLine("My favorite fruit is: {0}", name);
};
fruit("Cherry");
}
}
Output
My favorite fruit is: Cherry
In above example:
- delegate string fruitName(string name); declares a delegate named fruitName that…