In this article we are going to discuss how to implement Anonymous delegate with example in C#.
Anonymous Delegate Introduction
Delegates pointing methods without name using the delegate keyword are called anonymous delegates. Anonymous methods can be useful for short pieces of code that will only be used once or in situations where the method does not need a separate definition.
Why use anonymous delegates?
Example
using System;
namespace delegateproject
{
public delegate void AddDelegate(int a, int b);
class Program
{
static void Main()
{
// Create an instance of the delegate and assign it an anonymous method
AddDelegate ad = delegate (int a, int b)
{
Console.WriteLine("Addition of Two Number : "+ (a + b));
};
// Invoke the delegate
ad(30, 40);
Console.ReadLine();
}
}
}
In this updated version, the AddDelegate is assigned an anonymous method directly within the Main method. The method takes two parameters, a and b, and prints their sum. The Program class no longer needs the Add method, as the functionality has been moved to the anonymous method.
Output