Member-only story

Anonymous Method in C# with Examples

Shahzad Aslam
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.

Anonymous Method in C# with Examples

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:

  1. delegate string fruitName(string name); declares a delegate named fruitName that…

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

No responses yet