Csharp Anonymous Methods
# C# Anonymous Methods
In C#, an anonymous function is a method without a name that can be defined and used within code.
We have already mentioned that a delegate is used to reference a method with the same signature. In other words, you can use a delegate object to invoke a method that can be referenced by the delegate.
**Anonymous methods** provide a technique for passing a block of code as a delegate parameter.
In an anonymous method, you do not need to specify the return type; it is inferred from the return statement within the method body.
A lambda expression is a concise syntax for creating anonymous functions. They are commonly used in LINQ queries and with delegates.
### Syntax
```csharp
(parameters) => expression // or (parameters) => { statement; }
## Examples
```csharp
// Example: Using a lambda expression to define a delegate
Func add = (a, b) => a + b;
Console.WriteLine(add(2, 3)); // Outputs 5
// Example: Using a lambda expression to filter elements in an array
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // Outputs 2 4
}
Anonymous methods are declared by creating a delegate instance using the **delegate** keyword.
### Syntax
```csharp
delegate(parameters) { statement; }
For example:
```csharp
delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
The code block `Console.WriteLine("Anonymous Method: {0}", x);` is the body of the anonymous method.
A delegate can be invoked using an anonymous method or a named method, i.e., by passing method parameters to the delegate object.
**Note:** A `;` is required after the body of an anonymous method.
For example:
```csharp
nc(10);
## Examples
```csharp
// Example: Using an anonymous method to define a delegate
Func multiply = delegate(int a, int b)
{
return a * b;
};
Console.WriteLine(multiply(2, 3)); // Outputs 6
// Example: Using an anonymous method as an event handler
Button button = new Button();
button.Click += delegate(object sender, EventArgs e)
{
Console.WriteLine("Button clicked!");
};
The following example demonstrates the concept of anonymous methods:
## Examples
```csharp
using System;
delegate void NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static void AddNum(int p)
{
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void MultNum(int q)
{
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
static void Main(string[] args)
{
// Create delegate instance using anonymous method
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
// Invoke delegate using anonymous method
nc(10);
// Instantiate delegate using named method
nc = new NumberChanger(AddNum);
// Invoke delegate using named method
nc(5);
// Instantiate delegate using another named method
nc = new NumberChanger(MultNum);
// Invoke delegate using named method
nc(2);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Anonymous Method: 10
Named Method: 15
Named Method: 30
In C# 2.0 and later, lambda expressions were introduced, which is a more concise syntax for writing anonymous methods.
Using a lambda expression:
## Examples
```csharp
using System;
delegate void NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static void AddNum(int p)
{
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void MultNum(int q)
{
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
static void Main(string[] args)
{
// Create delegate instance using lambda expression
NumberChanger nc = x => Console.WriteLine($"Lambda Expression: {x}");
// Invoke delegate using lambda expression
nc(10);
// Instantiate delegate using named method
nc = new NumberChanger(AddNum);
// Invoke delegate using named method
nc(5);
// Instantiate delegate using another named method
nc = new NumberChanger(MultNum);
// Invoke delegate using named method
nc(2);
Console.ReadKey();
}
}
}
YouTip