What is a Delegate in C#?

In simple words, a delegate in C# is like a pointer to a function. It allows you to pass methods as arguments to other methods. Delegates are used to define callback methods and implement event handling.

Real-Life Analogy

Think of a delegate as a remote control for a TV. The remote control doesn't know or care which brand of TV it's controlling; it just sends signals to perform actions like turning the TV on or off, changing the channel, or adjusting the volume. Similarly, a delegate doesn't know the specifics of the method it references; it just calls the method when needed.

Example Scenario

Let's say you have a notification system where you want to send notifications through different channels like email, SMS, or push notifications. You can define a delegate that represents the method signature for sending notifications. Then, you can create methods for each notification type and assign them to the delegate as needed.

Simple Code Example

using System;

namespace DelegateExample
    // Step 1: Define a delegate
    public delegate void Notify(string message);

    class Program
        // Step 2: Create methods that match the delegate signature
        static void EmailNotification(string message)
            Console.WriteLine($"Email: {message}");

        static void SMSNotification(string message)
            Console.WriteLine($"SMS: {message}");

        static void Main(string[] args)
            // Step 3: Create delegate instances and assign methods to them
            Notify notifyByEmail = new Notify(EmailNotification);
            Notify notifyBySMS = new Notify(SMSNotification);

            // Step 4: Use the delegate instances to call the methods
            notifyByEmail("You've got mail!");
            notifyBySMS("You've got a text message!");

            // Alternatively, you can use the delegate directly with method group conversion
            Notify notify;
            notify = EmailNotification;
            notify("Email notification via delegate");

            notify = SMSNotification;
            notify("SMS notification via delegate");

Steps Explained:

  • Define a Delegate: The Notify delegate specifies a method signature with a string parameter and no return type.
  • Create Methods: EmailNotification and SMSNotification methods match the delegate's signature.
  • Create Delegate Instances: You create instances of the Notify delegate and assign methods to them.
  • Use the Delegate Instances: Call the methods through the delegate instances.

This way, you can easily switch or add new notification methods without changing the code that calls the delegate. The delegate acts as an intermediary, making your code more flexible and extensible.