🟢 1. Delegate
-
Think of it as: A variable that can store a method.
-
Purpose: Let you pass methods around like data.
-
Analogy: A remote control that can point to different TVs (methods).
Example
// Define a delegate type (method signature)
public delegate void MyDelegate(string msg);
class Program
{
static void Print(string m) => Console.WriteLine(m);
static void Main()
{
MyDelegate d = Print; // store method in delegate
d("Hello from delegate"); // call it
}
}
-
You can assign, combine, or call (
d(...)
) a delegate directly.
🟢 2. Event
-
Think of it as: A special wrapper around a delegate used for notifications.
-
Purpose: Publisher/Subscriber system — when something happens, tell all listeners.
-
Analogy: A doorbell. Many people can listen (subscribe). Only the house owner can ring (raise) it.
Example
using System;
class Door
{
public event Action DoorOpened; // event based on built-in delegate
public void Open()
{
Console.WriteLine("Door opened");
DoorOpened?.Invoke(); // only Door can trigger
}
}
class Program
{
static void Main()
{
var door = new Door();
door.DoorOpened += () => Console.WriteLine("Guest notified!");
door.Open();
}
}
-
Others use
+=
or-=
to subscribe/unsubscribe. -
Only the class that defines the event can raise (
Invoke
) it.
🟢 Key Differences
Feature | Delegate | Event |
---|---|---|
What is it? | Type-safe reference to a method | A delegate with extra rules for publish/subscribe |
Who can call (invoke)? | Anyone holding the delegate | Only the declaring class |
Usage | Pass methods as parameters, callbacks | Notify subscribers when something happens |
Subscription | Not required; can directly assign | Must use += or -= |
Encapsulation | None | Provides safety: outsiders can’t overwrite the list |
🟢 Simple Rule
-
Delegate: “Point to a method and call it.”
-
Event: “Many listeners can sign up; only the owner can fire it.”
Tiny Summary
-
Delegate = function pointer (method reference).
-
Event = delegate used for notifications with extra safety and
+=
/-=
subscription.
No comments:
Post a Comment