Delegate — type-safe function pointer. Event — mechanism for notifications.
Delegate:
1// Define delegate2public delegate void NotifyHandler(string message);34// Use delegate5public class Publisher {6 public NotifyHandler OnNotify;78 public void DoSomething() {9 OnNotify?.Invoke("Done!");10 }11}
Event:
1public class Publisher {2 // Event3 public event NotifyHandler OnNotify;45 public void DoSomething() {6 OnNotify?.Invoke("Done!"); // OK — same class7 }8}910public class Subscriber {11 public void Subscribe(Publisher p) {12 p.OnNotify += HandleNotify; // OK — subscribe13 p.OnNotify?.Invoke("Hi"); // Error! Cannot invoke14 }15}
Key differences: