Delegate Vs Event

 

✅ What are Delegates in C#?

delegate is a type-safe function pointer. It holds references to one or more methods with a specific signature and return type.


✅ Why Use Delegates?

ReasonDescription
FlexibilityPass methods as parameters (i.e., callbacks).
ExtensibilityDynamically assign behavior at runtime.
DecouplingLoosely couples components.
Foundation for EventsEvents use delegates under the hood.

🟢 Delegate Example – Less Safe (Public Access)


using System;

namespace DemoDelegate
{
    // 1. Define the delegate type
    public delegate void NotifyDelegate(string name);

    public class MyDelegateClass
    {
        // 2. Public delegate field (unsafe)
        public NotifyDelegate Notify;

        public void Greet(string name)
        {
            Console.WriteLine("Hello, " + name);
        }

        public void Welcome(string name)
        {
            Console.WriteLine("Welcome, " + name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyDelegateClass obj = new MyDelegateClass();

            // ✅ Multicast: Add multiple methods
            obj.Notify += obj.Greet;
            obj.Notify += obj.Welcome;

            // ✅ Invoke from outside
            obj.Notify("Alice");

            // ✅ Reset delegate from outside (DANGEROUS)
            obj.Notify = null;

            // ❌ Can result in NullReferenceException if not handled
            if (obj.Notify != null)
                obj.Notify("Bob");
            else
                Console.WriteLine("Delegate is null! Unsafe call prevented.");

            Console.ReadKey();
        }
    }
}

✅ What are Events in C#?

An event is a wrapper around a delegate that provides a safe mechanism for publish-subscribe communication.

  • Events are typically used in UI frameworksreal-time systems, or event-driven architectures.

  • Only the class that declares the event can raise it. Other classes can subscribe/unsubscribe but not invoke.




🟢 Event Example – Safe Encapsulation


using System;

namespace DemoEvent
{
    // 1. Define the delegate type
    public delegate void NotifyDelegate(string name);

    public class MyEventClass
    {
        // 2. Declare event based on delegate
        public event NotifyDelegate NotifyEvent;

        public void Greet(string name)
        {
            Console.WriteLine("Hello, " + name);
        }

        public void Welcome(string name)
        {
            Console.WriteLine("Welcome, " + name);
        }

        // Method to trigger the event safely from within the class
        public void TriggerEvent(string name)
        {
            // ✅ Safe check and call from inside the class
            NotifyEvent?.Invoke(name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyEventClass obj = new MyEventClass();

            // ✅ Multicast: Add multiple methods
            obj.NotifyEvent += obj.Greet;
            obj.NotifyEvent += obj.Welcome;

            // ❌ Cannot invoke from outside the class
            // obj.NotifyEvent("Alice"); // ❌ Compilation error

            // ❌ Cannot reset to null from outside
            // obj.NotifyEvent = null; // ❌ Compilation error

            // ✅ Safe: Only class itself can invoke event
            obj.TriggerEvent("Alice");

            Console.ReadKey();
        }
    }
}


delegate is like a method reference. You can call it directly and even modify it externally.
An event is a safer and more restricted wrapper over a delegate that enforces encapsulation, allowing only the declaring class to trigger it.


🔍 Code Mapping

FeatureDelegate Example CodeEvent Example Code
Multicast✅ Notify += Method✅ NotifyEvent += Method
Invoke from outside class✅ Notify("Alice")❌ Compile-time error
Reset from outside✅ Notify = null;❌ Compile-time error
Encapsulation / Safety❌ Can break externally✅ Invoked only inside class
Access Limited to Class❌ Publicly accessible✅ Trigger only inside class

Comments

Popular posts from this blog

Interview Tips: Dot NET Framework vs Net CORE

FREE Webinar: Run Your Own Independent DeepSeek LLM

Delegates and Events