Autocoder

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 delegatesFunc, Action, Predicate, Comparison
Event patternEventHandler<TEventArgs>
Language versionC# 12 on .NET 8

Definitions to have ready

C# Delegates and Events Interview Questions: questions with worked answers

  1. 1

    What is a delegate and how do you declare and call one?

    easy

    A 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.

    csharp
    delegate 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)); // 6
  2. 2

    Func, Action and Predicate: what are they?

    easy

    Func<..., 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.

    csharp
    Func<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));  // True
  3. 3

    What is a multicast delegate? Predict the output and the return value.

    medium

    The += 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.

    csharp
    Func<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);  // 2
  4. 4

    How is an event different from a public delegate field?

    medium

    With 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.

    csharp
    public 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. 5

    Show the standard .NET event pattern.

    medium

    Define 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.

    csharp
    public 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 -> 10
  6. 6

    Predict the output: closures capturing loop variables.

    hard

    A 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.

    csharp
    var 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());     // 012
  7. 7

    How can events cause memory leaks, and how do you avoid it?

    medium

    The 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.

    csharp
    EventHandler 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 instance
  8. 8

    What are anonymous methods, lambdas and expression trees?

    medium

    An 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.

    csharp
    Func<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));                      // 6
  9. 9

    Explain covariance and contravariance for delegates.

    hard

    A 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.

    csharp
    Func<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");                         // hi
  10. 10

    Delegate versus interface: when do you choose each?

    medium

    Use 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. 11

    Why is async void common with events and what are the risks?

    medium

    Event 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.

    csharp
    button.Clicked += async (s, e) => {
        try { await SaveAsync(); }
        catch (Exception ex) { Log(ex); }
    };
  12. 12

    Is raising an event thread safe? What was the old null-check race?

    medium

    Before 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. 13

    What is the observer pattern, and how does IObservable<T> relate?

    medium

    The 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. 14

    What does a static lambda do?

    easy

    A 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.

    csharp
    Func<int, int> sq = static x => x * x;
    int k = 3;
    // Func<int,int> bad = static x => x * k;   // error: cannot capture k
  15. 15

    What happens when you compare delegates or subscribe the same method twice?

    medium

    Delegates 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.

    csharp
    Action 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

See all in this section