Learn about Delegates And Events

Delegates

One of Google's meanings of a Delegate is representative, so a Delegate means it represents something. In Programming, a delegate is a variable that holds the reference to a method or pointer to a method.

  • A delegate can refer to more than one method of the same return type and parameters.
  • The preferred methods must have the same signature(return type and parameters).
  • Syntax: Syntax
  • Delegate returnType DelegateName(parameters);
  • Delegates can be generic.
  • Public delegate T Operation<T>(T x, T y);
  • Delegates can be used to define callback methods.
  • A delegate is a type that safely encapsulates a method.

Types of Delegates

  • Single Delegate: In the definition only, defining single means it holds the single method reference.
  • Multicast Delegate: Multi means more than one, so it holds the references of more than one method.
  • Anonymous Delegates: Anonymous means no identity/No name, which means the delegate-referred method doesn't have any name.

Example

You are defining a class Vehicle with HeroHonda and KTM methods, which share the same signature. A delegate Bike can then be used to call either of these methods dynamically.

using System;

class Vehicle
{
    // Define methods with the same signature
    public void HeroHonda(string bikeMilage, string price)
    {
        Console.WriteLine($"Hero Honda: Mileage = {bikeMilage}, Price = {price}");
    }

    public void KTM(string bikeMilage, string price)
    {
        Console.WriteLine($"KTM: Mileage = {bikeMilage}, Price = {price}");
    }

    // Define a delegate with the same signature as the methods
    public delegate void Bikes(string bikeMilage, string price);

    static void Main(string[] args)
    {
        // Create an object of the Vehicle class
        Vehicle vehicle = new Vehicle();

        // Create a delegate instance pointing to HeroHonda
        Bikes bikeDelegate = vehicle.HeroHonda;
        bikeDelegate("45 kmpl", "85,000 INR"); // Calls HeroHonda

        // Reassign the delegate to point to KTM
        bikeDelegate = vehicle.KTM;
        bikeDelegate("30 kmpl", "2,50,000 INR"); // Calls KTM

        // Demonstrates the flexibility of delegates
    }
}

Output

Output

Events

To understand events, think of a real-world scenario

An event is like a celebration or function organized by a family. The family notifies others about the celebration using invitation cards, calls, or messages, letting them know something important is happening and inviting them to participate.

On the Programming side, an event means a notification mechanism. It allows a class to notify other classes or objects when something happens.

  • Events cannot be used without delegates.
  • Events use the Publisher - Subscriber mechanism.
  • Publisher: Detects the events, Deining the event, and raising the event.
  • Subscriber: Listen to the event and handle it.

Example

An example is an organization scenario where the HR raises an event to notify the Manager and Lead about organizational updates. The Manager and Lead handle these notifications (e.g., through email or other means).

using System;

namespace OrganizationEvents
{
    // Define delegate for the event
    public delegate void UpdateNotificationHandler(string message);

    // Publisher: HR class
    public class HR
    {
        // Event to notify updates
        public event UpdateNotificationHandler NotifyUpdates;

        // Method to trigger the notification event
        public void SendUpdate(string message)
        {
            Console.WriteLine("HR: Sending update...");
            NotifyUpdates?.Invoke(message); // Notify all subscribers
        }
    }

    // Subscriber: Manager class
    public class Manager
    {
        // Method to handle the notification
        public void ReceiveUpdate(string message)
        {
            Console.WriteLine($"Manager: Received update via email - {message}");
        }
    }

    // Subscriber: Lead class
    public class Lead
    {
        // Method to handle the notification
        public void ReceiveUpdate(string message)
        {
            Console.WriteLine($"Lead: Received update via notification - {message}");
        }
    }

    // Main Program
    class Program
    {
        static void Main(string[] args)
        {
            // Create instances of HR, Manager, and Lead
            var hr = new HR();
            var manager = new Manager();
            var lead = new Lead();

            // Subscribe Manager and Lead to HR's NotifyUpdates event
            hr.NotifyUpdates += manager.ReceiveUpdate;
            hr.NotifyUpdates += lead.ReceiveUpdate;

            // HR sends an update
            hr.SendUpdate("New policy update: Remote work is extended for 3 months.");

            // Another update
            hr.SendUpdate("Annual performance reviews start next week.");
        }
    }
}

Output

Output 2


Similar Articles