Anonymous Methods in C# Language
Anonymous methods in C# are a powerful feature that allows you to define and use delegate instances without
explicitly creating a named method. They provide a concise way to define inline, unnamed functions or code blocks. This feature is particularly useful when you need to pass a block of code as an argument to another method, such as in asynchronous operations or event handling. In this post, we will explore the concept of anonymous methods in C# and provide examples to help you understand their practical usage.Syntax of Anonymous Methods
An anonymous method is essentially a delegate that is defined without a name. It has the following basic syntax:
delegate(parameters)
{
// Code block
}
The delegate
keyword is followed by the parameter list, and then a code block enclosed in curly braces. You can use the parameters in your code block just like you would in a regular method.
Example 1: Basic Usage
Let’s start with a simple example where we use an anonymous method to perform a basic operation. Suppose we want to create a delegate that takes two integers and returns their sum.
using System;
class Program
{
delegate int ArithmeticOperation(int a, int b);
static void Main()
{
ArithmeticOperation add = delegate(int a, int b)
{
return a + b;
};
int result = add(5, 3);
Console.WriteLine("Sum: " + result); // Output: Sum: 8
}
}
In this example, we define an anonymous method within the delegate ArithmeticOperation
. The code block within the anonymous method calculates the sum of two integers.
Example 2: Event Handling
Anonymous methods are commonly used in event handling. Here’s an example of how to subscribe to an event using an anonymous method:
using System;
class Program
{
public event EventHandler MyEvent;
static void Main()
{
Program program = new Program();
program.MyEvent += delegate (object sender, EventArgs e)
{
Console.WriteLine("Event handled!");
};
program.RaiseEvent(); // This triggers the event
}
protected void RaiseEvent()
{
MyEvent?.Invoke(this, EventArgs.Empty);
}
}
In this example, we define an anonymous method to handle the MyEvent
event. When we raise the event, the anonymous method is executed, resulting in the “Event handled!” message being displayed.
Example 3: LINQ Expressions
Anonymous methods are also commonly used with LINQ expressions. Consider the following example where we use an anonymous method with LINQ to filter a list of numbers:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = numbers.Where(delegate (int n)
{
return n % 2 == 0;
});
Console.WriteLine("Even Numbers: " + string.Join(", ", evenNumbers)); // Output: Even Numbers: 2, 4, 6, 8, 10
}
}
In this example, we use an anonymous method with the Where
method to filter even numbers from the list.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.