BCA / B.Tech 9 min read

Delegates & Events

Delegates & Events in .NET in Hindi | Introduction to Delegates and Events:


Delegates

  • Delegates in C# are a type of reference type that refers to a method. 
  • In other words, delegates are used to refer to a method like a pointer. Delegates are used when we need to call a method at run-time.
  • Delegates are considered "type-safe" because they can only refer to methods whose signature (parameters and return type) matches the signature of the delegate.
Events

  • Events in C# are a mechanism based on delegates. Events are used when one class needs to inform another class about a particular situation.
  • For example, when a button is pressed, a "click" event is triggered.

To work with delegates and events, we need to follow these steps:

  • Define the delegate.
  • Create an object of the delegate.
  • Declare the event.
  • Subscribe to and trigger the event.
  • Simple program: Using delegates and events

Below is an example that explains delegates and events:

using System;

namespace DelegatesAndEventsExample
{
    // Step 1: Define a delegate
    public delegate void NotifyHandler(string message);

    // Publisher class
    public class Publisher
    {
        // Step 2: Declare an event using the delegate
        public event NotifyHandler Notify;

        public void TriggerEvent(string message)
        {
            // Step 3: Trigger the event
            if (Notify != null)
            {
                Notify(message); // Notify all subscribers
            }
        }
    }

    // Subscriber class
    public class Subscriber
    {
        public void OnNotifyReceived(string message)
        {
            Console.WriteLine("Subscriber received message: " + message);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Create publisher and subscriber objects
            Publisher publisher = new Publisher();
            Subscriber subscriber = new Subscriber();

            // Step 4: Subscribe to the event
            publisher.Notify += subscriber.OnNotifyReceived;

            // Trigger the event
            publisher.TriggerEvent("Hello, this is a test event!");

            Console.ReadLine();
        }
    }
}

How it works:

  • A delegate named NotifyHandler was defined, which will refer to a method as a pointer.
  • An event Notify was declared in the Publisher class.
  • The OnNotifyReceived method was defined in the Subscriber class, which acts as an event handler.
  • In Main(), the Publisher event was subscribed to with the Subscriber's method and then the event was triggered.

Output:

Subscriber received message: Hello, this is a test event!

This example helps to explain delegates and events in a simple and practical way.