Delegates, Events & Lambdas

17 questions found

What is a delegate in C#?

Beginner
A delegate is a type-safe reference to a method, letting you pass behaviour as a parameter and invoke it later. Func<>, Action<> and Predicate<> are built-in delegates.
Func<int,int> square = x => x*x;
Action<string> log = Console.WriteLine;
Console.WriteLine(square(4)); // 16
Real-world example Passing a comparison or projection function into a sorting or LINQ method.

What is the difference between Func, Action and Predicate?

Beginner
Func<...,TResult> returns a value; Action<...> returns void; Predicate<T> is a Func<T,bool> used for tests.
Func<int,bool> isEven = n => n%2==0;
Action greet = () => Console.Write("hi");
Real-world example Passing isEven to List.FindAll to filter numbers.

What is a closure and what is a common pitfall?

Intermediate
A closure is a lambda that captures variables from its enclosing scope. A classic pitfall is capturing a loop variable by reference so all lambdas see its final value.
var fns = new List<Func<int>>();
foreach (var i in Enumerable.Range(0,3)) fns.Add(() => i); // each captures its own i (C# 5+)
Real-world example Building event handlers in a loop that must remember the item they were created for.

How do events differ from plain delegates?

Intermediate
An event is a delegate wrapped so external code can only subscribe (+=) or unsubscribe (-=), not invoke or overwrite it — enforcing the publisher/subscriber boundary.
public event EventHandler? Saved;
protected void OnSaved() => Saved?.Invoke(this, EventArgs.Empty);
Real-world example A ViewModel raises a Saved event that views subscribe to, without views being able to fire it.

What causes event-handler memory leaks and how do you prevent them?

Advanced
A long-lived publisher holding a delegate to a subscriber keeps the subscriber alive. Prevent it by unsubscribing (-=), using weak event patterns, or scoping lifetimes.
source.Changed += Handler;
// later, to allow GC:
source.Changed -= Handler;
Real-world example A screen that subscribes to a singleton service must unsubscribe on close or it never gets collected.

What is the difference between multicast delegate invocation and exception handling?

Advanced
A multicast delegate invokes subscribers in order; if one throws, later subscribers are skipped and the exception propagates. Invoke manually via GetInvocationList to isolate failures.
foreach (var d in handler.GetInvocationList().Cast<Action>())
    try { d(); } catch (Exception ex) { Log(ex); }
Real-world example Notifying many listeners where one failing listener must not block the rest.

What is a delegate in C#, and what does it represent conceptually?

Beginner
A delegate is a type-safe reference to a method with a specific signature — it lets you treat methods as values you can store in variables, pass as parameters, and invoke indirectly, similar to a function pointer but fully type-checked by the compiler.
public delegate int MathOperation(int a, int b);

int Add(int a, int b) => a + b;
MathOperation op = Add;
int result = op(3, 4); // 7, invoked through the delegate
Real-world example Passing a specific comparison or transformation method as an argument to a generic sorting or processing function.

Common follow-ups: How does a delegate differ from simply calling a method directly?

Interfaces & Abstract Classes

How do you write and use a lambda expression as a shorthand for a delegate?

Beginner
A lambda expression `(parameters) => expression` provides a concise, inline way to define a small function without a separate named method declaration — it can be assigned directly to any compatible delegate type, including built-in ones like Func<> and Action<>.
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(3, 4)); // 7

Action<string> greet = name => Console.WriteLine($"Hello, {name}");
greet("Sam");
Real-world example Passing a short, inline comparison or filtering expression directly to a LINQ method like Where() or OrderBy().

Common follow-ups: What's the difference between the built-in Func<> and Action<> delegate types?

LINQ

What is an event, and how does it differ from a plain public delegate field?

Intermediate
An event wraps a delegate but RESTRICTS external code to only += (subscribe) and -= (unsubscribe) — external code can't directly invoke the event or overwrite its entire subscriber list with '=', which a plain public delegate field would allow, protecting the publishing class's control over when the event actually fires.
public class Button {
  public event EventHandler? Clicked; // safe: outside code can only += or -=
  public void SimulateClick() => Clicked?.Invoke(this, EventArgs.Empty);
}

var button = new Button();
button.Clicked += (sender, e) => Console.WriteLine("Clicked!");
// button.Clicked = null; // Error: can't do this from outside the class
Real-world example Implementing a UI button's Click event, or a domain model's OnOrderPlaced event that other parts of the system subscribe to.

Common follow-ups: Why is the null-conditional operator (?.Invoke) commonly used when raising an event?

Interfaces & Abstract Classes

What are multicast delegates, and in what order do their subscribed methods get invoked?

Intermediate
A delegate can hold references to MULTIPLE methods simultaneously (added via +=), forming an invocation LIST — calling the delegate invokes every subscribed method IN THE ORDER they were added, one after another, sequentially on the same thread.
Action greetings = null;
greetings += () => Console.WriteLine("Hello");
greetings += () => Console.WriteLine("Hi");
greetings += () => Console.WriteLine("Hey");
greetings?.Invoke(); // prints Hello, Hi, Hey in that order
Real-world example Allowing multiple independent parts of an application to subscribe to and react to the same event, like a logging system and a UI update both reacting to OnDataChanged.

Common follow-ups: What happens to the RETURN VALUE if a multicast delegate has a non-void return type and multiple subscribers?

LINQ

Showing 1–10 of 17