Delegate Vs Event
✅ What are Delegates in C#?
A 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?
Reason | Description |
---|---|
Flexibility | Pass methods as parameters (i.e., callbacks). |
Extensibility | Dynamically assign behavior at runtime. |
Decoupling | Loosely couples components. |
Foundation for Events | Events 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 frameworks, real-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();
}
}
}
A 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.
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
Feature | Delegate Example Code | Event 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
Post a Comment