Explain delegates, Func, Action, and events in C# — when do you use each?
cs-mid-005
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
A delegate is a type-safe function pointer. Func<T,TResult> and Action<T> are built-in generic delegate types — Func returns a value, Action does not. You use them to pass behaviour as a parameter (strategy pattern, callbacks). An event is a delegate field protected by add/remove accessor conventions; only the declaring class can invoke it, which prevents external code from firing or clearing the event list. Use Func/Action for one-off callbacks; use events when multiple subscribers need loose-coupled notification (e.g., UI event model, domain events). Avoid returning void in async delegates — prefer Func<Task>.
Code example
// Func (returns a value)
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4)); // 7
// Action (void return)
Action<string> log = msg => Console.WriteLine($"[LOG] {msg}");
log("started");
// Predicate (shorthand for Func<T, bool>)
Predicate<int> isEven = n => n % 2 == 0;
// Custom delegate + event pattern
public class OrderProcessor
{
public event EventHandler<OrderEventArgs> OrderPlaced;
public void Process(Order order)
{
// ... processing ...
OrderPlaced?.Invoke(this, new OrderEventArgs(order));
}
}
// Higher-order function using Func
public IEnumerable<T> Filter<T>(IEnumerable<T> source, Func<T, bool> predicate)
=> source.Where(predicate);
Follow-up
What is multicast delegation? What happens if one delegate in a multicast chain throws an exception?