C# Delegates and Events Interview Questions
Last updated 2026-11-19
Delegates and events are the part of C# that candidates use daily and explain badly. Interviewers ask what a delegate really is, how multicast invocation works, why an event is not just a public delegate field, and how closures capture loop variables.
The answers use C# 12. Delegates underlie LINQ, so read them together with the LINQ questions, and with async and await for the async event handler issue.
| Built-in generic delegates | Func, Action, Predicate, Comparison |
|---|---|
| Event pattern | EventHandler<TEventArgs> |
| Language version | C# 12 on .NET 8 |
Definitions to have ready
- Delegate: a type-safe reference to a method, with a signature checked at compile time.
- Multicast delegate: one delegate instance holding an invocation list of several methods.
- Event: a delegate field with restricted access, so outside code can only subscribe and unsubscribe.
- Closure: a lambda that captures variables from its enclosing scope.
C# Delegates and Events Interview Questions: questions with worked answers
1 What is a delegate and how do you declare and call one?
easyA delegate is a type that represents references to methods with a given parameter list and return type, like a type-safe function pointer that is also an object. You declare it with the delegate keyword, assign a method group or lambda to an instance and invoke it like a method. Delegates are immutable reference types derived from System.Delegate.
csharpdelegate int BinaryOp(int a, int b); static int Add(int a, int b) => a + b; BinaryOp op = Add; // method group conversion Console.WriteLine(op(2, 3)); // 5 op = (a, b) => a * b; Console.WriteLine(op.Invoke(2, 3)); // 62 Func, Action and Predicate: what are they?
easyFunc<..., TResult> takes up to 16 parameters and returns a value, the last type argument being the return type. Action<...> takes parameters and returns void. Predicate<T> is Func<T, bool> from before generics matured and is used by List<T>.Exists and FindAll. Prefer these over declaring custom delegate types unless the name documents intent.
csharpFunc<int, int, int> add = (a, b) => a + b; Action<string> log = s => Console.WriteLine(s); Predicate<int> even = n => n % 2 == 0; log(add(1, 2).ToString()); // 3 Console.WriteLine(even(4)); // True3 What is a multicast delegate? Predict the output and the return value.
mediumThe += operator combines delegates into one invocation list that is called in order of subscription, and -= removes the last matching entry. If the delegate returns a value, only the last method result is returned. If one method throws, the remaining ones in the list do not run.
csharpFunc<int> f = () => { Console.Write("A "); return 1; }; f += () => { Console.Write("B "); return 2; }; int r = f(); // prints "A B " Console.WriteLine(r); // 2 Console.WriteLine(f.GetInvocationList().Length); // 24 How is an event different from a public delegate field?
mediumWith a public delegate field any outside code can invoke it, replace all subscribers with = or clear it. The event keyword restricts outside code to += and -=, and only the declaring class can raise it. It is the encapsulation of a delegate, the same way a property encapsulates a field. The compiler generates add and remove accessors, which you can customise.
csharppublic class Button { public event EventHandler? Clicked; // outside code can only += and -= public Action? RawHandler; // anyone can do btn.RawHandler = null public void Click() => Clicked?.Invoke(this, EventArgs.Empty); }5 Show the standard .NET event pattern.
mediumDefine an EventArgs subclass for the data, declare an event of type EventHandler<TEventArgs>, raise it from a protected virtual On method so derived classes can hook in, and invoke with the null-conditional operator so there is no race between the null check and the call. The first argument is the sender and the second the event data.
csharppublic class PriceChangedEventArgs(decimal oldP, decimal newP) : EventArgs { public decimal Old { get; } = oldP; public decimal New { get; } = newP; } public class Stock { private decimal _price; public event EventHandler<PriceChangedEventArgs>? PriceChanged; protected virtual void OnPriceChanged(PriceChangedEventArgs e) => PriceChanged?.Invoke(this, e); public decimal Price { get => _price; set { if (value != _price) { var old = _price; _price = value; OnPriceChanged(new(old, value)); } } } } var s = new Stock(); s.PriceChanged += (_, e) => Console.WriteLine($"{e.Old} -> {e.New}"); s.Price = 10; // 0 -> 106 Predict the output: closures capturing loop variables.
hardA lambda captures the variable, not its current value. A for loop declares one i shared by every iteration, so all lambdas see its final value 3. In a foreach loop each iteration has its own variable (since C# 5), so each lambda sees its own element.
csharpvar fs = new List<Func<int>>(); for (int i = 0; i < 3; i++) fs.Add(() => i); foreach (var f in fs) Console.Write(f()); // 333 var gs = new List<Func<int>>(); foreach (var n in new[] { 0, 1, 2 }) gs.Add(() => n); foreach (var g in gs) Console.Write(g()); // 0127 How can events cause memory leaks, and how do you avoid it?
mediumThe publisher holds a reference to each subscriber through its delegate list, so a long-lived publisher (a static event, a singleton, a shared service) keeps short-lived subscribers alive after you think they are gone. Always unsubscribe with -= when the subscriber is disposed, implement IDisposable for that, or use a weak event pattern such as WeakReference or WeakEventManager in WPF. Unsubscribing a lambda does not work unless you keep the same delegate instance in a variable.
csharpEventHandler h = (s, e) => Console.WriteLine("hit"); button.Clicked += h; button.Clicked -= h; // works: same instance button.Clicked += (s, e) => { }; button.Clicked -= (s, e) => { }; // does NOT remove: different instance8 What are anonymous methods, lambdas and expression trees?
mediumAn anonymous method (delegate { ... }) and a lambda ((x) => ...) both create a delegate inline; lambdas are shorter and can omit parameter types. A lambda converted to Expression<Func<...>> instead produces an expression tree, data describing the code that a provider such as EF Core can translate to SQL. Func runs in memory; Expression<Func> can be inspected. C# 12 lets lambdas have default parameter values.
csharpFunc<int, bool> f = x => x > 5; // executable delegate Expression<Func<int, bool>> e = x => x > 5; // expression tree Console.WriteLine(e.Body); // (x > 5) var inc = (int x, int step = 1) => x + step; // C# 12 default parameter Console.WriteLine(inc(5)); // 69 Explain covariance and contravariance for delegates.
hardA delegate return type can be covariant: a method returning a more derived type can be assigned to a delegate returning a base type. Parameters can be contravariant: a method accepting a base type can be assigned to a delegate whose parameter is a derived type. Generic delegates declare this with out and in, as in Func<out TResult> and Action<in T>, so an Action<object> can be used where an Action<string> is expected.
csharpFunc<string> getS = () => "x"; Func<object> getO = getS; // covariance: string to object Action<object> actO = o => Console.WriteLine(o); Action<string> actS = actO; // contravariance: object accepts string actS("hi"); // hi10 Delegate versus interface: when do you choose each?
mediumUse a delegate (or Func and Action) for a single-method contract, callbacks and strategy hooks, where a lambda is the natural implementation. Use an interface when a contract has several related methods, needs state and identity, or benefits from dependency injection registration. A one-method interface is often replaced by a delegate, which is lighter but harder to mock by name.
11 Why is async void common with events and what are the risks?
mediumEvent handlers must return void, so async handlers are written as async void, and an unhandled exception in them escapes to the synchronisation context and can crash the application. Wrap the body in try and catch, or have the handler call an async Task method and observe its result. Libraries that need async events define their own delegate returning Task and invoke the list with await.
csharpbutton.Clicked += async (s, e) => { try { await SaveAsync(); } catch (Exception ex) { Log(ex); } };12 Is raising an event thread safe? What was the old null-check race?
mediumBefore the null-conditional operator, code checked if (Handler != null) Handler(...), and another thread could unsubscribe the last handler between the check and the call, causing a NullReferenceException. The fix was to copy the field to a local first, and Handler?.Invoke(...) does exactly that atomically. Handlers still run on the raising thread, so they must be thread safe themselves.
13 What is the observer pattern, and how does IObservable<T> relate?
mediumThe observer pattern lets subjects notify subscribers of changes without knowing them, and C# events are its built-in form. IObservable<T> and IObserver<T> generalise it into push-based streams with OnNext, OnError and OnCompleted, which Reactive Extensions builds on. INotifyPropertyChanged is the event-based form used for data binding in WPF and MAUI.
14 What does a static lambda do?
easyA static lambda (C# 9) cannot capture local variables or this, so the compiler can cache a single delegate instance and avoid allocating a closure. Marking hot-path lambdas static documents and enforces that they are non-capturing.
csharpFunc<int, int> sq = static x => x * x; int k = 3; // Func<int,int> bad = static x => x * k; // error: cannot capture k15 What happens when you compare delegates or subscribe the same method twice?
mediumDelegates are equal when they have the same type, target and method, so subscribing the same method twice adds it to the list twice and it runs twice, and each -= removes one. Two separate lambdas with identical text are different instances and compare unequal. Check for duplicates with GetInvocationList if that matters.
csharpAction a = () => Console.Write("x"); Action twice = a; twice += a; twice(); // xx twice -= a; twice(); // x
Frequently asked questions
What is the difference between delegates and events in one line?
An event is a delegate with restricted access: outside code can subscribe and unsubscribe but not invoke or reset it.
Are delegates reference types?
Yes. Delegate instances are immutable objects, so += creates a new combined instance.
What are delegates used for in .NET?
Callbacks, LINQ predicates and selectors, event handling, strategies, and middleware in ASP.NET Core are all delegates. See .NET Core questions.
How do lambdas relate to delegates?
A lambda is a compact way to create a delegate instance or an expression tree.
Related guides
More in Programming Language Interview Questions by Language
- C# Interview Questions and Answers
- C# LINQ Interview Questions
- C# OOPs Interview Questions
- C++ Coding Interview Questions
- C++ Interview Questions and Answers
- C++ Memory Management Interview Questions
- C++ OOPS Interview Questions
- C++ Pointers and References Interview Questions
- C++ Smart Pointers Interview Questions
- C++ STL Interview Questions
- C++ Templates Interview Questions
- C++ Virtual Functions Interview Questions