Delegates & Events in C#

Callbacks, decoupling, and the backbone of async .NET

60-Second Version: A delegate is a type-safe function pointer. Events are delegates with publisher restrictions. Think of Kunal ordering pizza.

1. Why Do We Need Delegates?

You want to pass behavior as a parameter. Kunal wants to tell the delivery guy what to do when pizza arrives: call, ring bell, or leave at door. Instead of hardcoding, pass the action.

// Declare: what kind of action?
public delegate void PizzaArrivedAction(string address);

// Use: Kunal passes his choice
PizzaArrivedAction action = KunalCallMe;
action("123 Main St"); // Calls KunalCallMe

2. Multicast: One Call, Many Actions

Delegates can chain methods with +=. When pizza arrives, call Kunal AND Prerna AND notify security.

action += PrernaMessageMe;
action += SecurityLog;
// One invoke โ†’ all 3 run in order

3. Events: Delegates With Guardrails

event keyword means only the publisher can invoke. Kaushal owns the pizza tracker. Others can only subscribe += or unsubscribe -=. They can't fire it or reset it.

public class PizzaTracker {
    public event PizzaArrivedAction OnArrived; // Safe
    public void DeliverPizza() { OnArrived?.Invoke("123 Main St"); } // Only I can call
}
Beginner Trap: Forgetting to unsubscribe from events in UI controls. Sanju's form closes but the event still holds reference. App never releases memory. Always -= in Dispose or on close.

Quick Check ๐Ÿง 

Comments on Delegates & Events (0)

No comments yet. Be the first to share your thoughts!