Anonymous Delegates in C#


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?

  1. Simplified Code - Anonymous methods can make the code simpler and more readable by reducing the need to define separate, named methods for small pieces of functionality that are only used once.
  2. Encapsulation - They help in encapsulating code that is only relevant within a specific context, avoiding the pollution of the class with multiple small methods that are not meant to be reused elsewhere.
  3. Event Handling - Anonymous methods are particularly useful in event handling, where the event handler logic is often short and specific to the context in which it is used.
  4. Inline Definition- By defining the method inline, it is easier to understand the code flow and see the logic in the place where it is being used, enhancing readability and maintainability.

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

Anonymous Delegate in C#
Prev Next