Interview frequency: …
Short answer
A Delegate is a type-safe function pointer; Func returns a value and Action returns nothing. The event keyword prevents external subscribers from invoking the event or clearing its listener list; they can only use += and -=.
Explanation
A Delegate is a type that represents a function signature. Instead of defining a custom delegate for every case, Microsoft provides Func<T, TResult> for functions with return values and Action<T> for void functions. Adding the event keyword to a delegate protects Encapsulation: code outside the class cannot invoke the event or clear other listeners with = null; it can only subscribe with += and unsubscribe with -=.
Code example
public class OrderProcessor {
public event Action<Order>? OrderCompleted;
public void Process(Order order) {
OrderCompleted?.Invoke(order); // Only invoked from within the class
}
}Common mistakes
- Not unsubscribing from events (-=) on long-lived objects, preventing the Garbage Collector from reclaiming listener objects and causing a memory leak.