Skip to main content
C# Fundamentals for Beginners to Advanced
CHAPTER 23 Beginner

Delegates, Events, and Lambda Expressions

Updated: May 17, 2026
5 min read

# CHAPTER 23

Delegates, Events, and Lambda Expressions

1. Introduction

What if you wanted to pass a *method* as a parameter to another method? What if you want a button click to notify 5 different classes automatically? Delegates and Events form the backbone of C#'s event-driven architecture (essential for UI frameworks like WPF, Unity, and ASP.NET).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand what a Delegate is (a pointer to a function).
  • Use the built-in Action and Func delegates.
  • Implement publisher-subscriber architecture using event.
  • Understand Lambda Expressions deeply.

3. What is a Delegate?

A Delegate is a type that safely encapsulates a method. Think of it as a variable that holds a method instead of a number or a string.
csharp
123456789101112131415161718192021
using System;

class Program
{
    // 1. Define the Delegate signature (Must match the method it will hold)
    public delegate void PrintDelegate(string message);

    static void PrintToConsole(string msg) { Console.WriteLine($"Console: {msg}"); }
    static void PrintToUpper(string msg) { Console.WriteLine($"UPPER: {msg.ToUpper()}"); }

    static void Main()
    {
        // 2. Instantiate the delegate and point it to a method
        PrintDelegate myPrinter = PrintToConsole;
        myPrinter("Hello!"); // Executes PrintToConsole("Hello!")

        // 3. Reassign it!
        myPrinter = PrintToUpper;
        myPrinter("Hello!"); // Executes PrintToUpper("Hello!")
    }
}

4. Action and Func (Modern Delegates)

Declaring custom delegates via public delegate... is the old way. Modern C# provides built-in generic delegates to save time:
  • Action<T>: Points to a method that returns void.
  • Func<T, TResult>: Points to a method that returns a value (the last parameter is the return type).
csharp
1234567
// Action (Returns void, takes a string)
Action<string> modernPrinter = PrintToConsole;
modernPrinter("Using Action!");

// Func (Takes an int, returns an int)
Func<int, int> squareNumber = (x) => x * x; // Using a Lambda Expression!
Console.WriteLine(squareNumber(5)); // Prints 25

5. Events (Publisher / Subscriber)

An event is a special type of delegate used to broadcast notifications.
  • Publisher: The class that triggers (fires) the event.
  • Subscriber: The classes that listen for the event.

Imagine an alarm system.

csharp
1234567891011121314151617181920212223242526272829303132333435
// 1. The Publisher
class AlarmClock
{
    // Define the Event
    public event Action OnRing;

    public void TriggerAlarm()
    {
        Console.WriteLine("Clock hits 7:00 AM!");
        // Check if anyone is listening, then FIRE the event!
        if (OnRing != null) 
        {
            OnRing.Invoke(); 
        }
    }
}

// 2. The Subscribers
class Program
{
    static void WakeUpPerson() { Console.WriteLine("Person: Waking up!"); }
    static void TurnOnCoffeeMaker() { Console.WriteLine("Coffee Maker: Brewing coffee..."); }

    static void Main()
    {
        AlarmClock clock = new AlarmClock();

        // Subscribe to the event using +=
        clock.OnRing += WakeUpPerson;
        clock.OnRing += TurnOnCoffeeMaker;

        // Triggering the alarm automatically calls BOTH subscribed methods!
        clock.TriggerAlarm();
    }
}

6. Lambda Expressions

We saw Lambda expressions (=>) in Chapter 21 with LINQ. They are simply anonymous (unnamed) methods written inline. They are heavily used to subscribe to events quickly.
csharp
123456
AlarmClock myClock = new AlarmClock();

// Subscribing with a Lambda instead of creating a whole new method!
myClock.OnRing += () => Console.WriteLine("Lambda: Doing something quick!");

myClock.TriggerAlarm();

7. Common Mistakes

  • Using = instead of += for Events: If you write clock.OnRing = WakeUpPerson;, you completely erase all previous subscribers! Always use += to subscribe and -= to unsubscribe.
  • Memory Leaks with Events: If an object subscribes to a static event but forgets to unsubscribe (-=) before being destroyed, the event will keep the object alive in memory permanently.

8. Best Practices

  • Never fire an event without checking if it is null first (e.g., OnRing?.Invoke();). If an event has no subscribers, calling .Invoke() will throw a NullReferenceException.

9. Exercises

  1. 1. Create a delegate MathOp that takes two ints and returns an int. Point it to an Add method, then reassign it to a Multiply method.
  1. 2. Rewrite exercise 1 using the built-in Func<int, int, int> delegate.

10. MCQs with Answers

Question 1

What is a Delegate in C#?

Question 2

Which built-in generic delegate represents a method that returns void?

Question 3

Which built-in generic delegate represents a method that returns a value?

Question 4

In Func<int, string>, what does the method return?

Question 5

What is an Event in C#?

Question 6

Which operator is used to SUBSCRIBE to an event?

Question 7

Which operator is used to UNSUBSCRIBE from an event?

Question 8

What happens if you .Invoke() an event that has zero subscribers?

Question 9

What does the ?. operator do in MyEvent?.Invoke();?

Question 10

Lambda expressions are essentially:

11. Interview Questions

  • Q: Explain the difference between Action, Func, and Predicate.
  • Q: What is the Publisher/Subscriber pattern, and how do C# Events facilitate it?

12. Summary

Delegates treat methods as data, allowing you to pass them around as variables. Modern C# uses Action and Func to simplify this. By layering the event keyword on top of delegates, you can build highly decoupled Publisher-Subscriber architectures, which are the foundation of modern UI and reactive programming.

13. Next Chapter Recommendation

In Chapter 24: Multithreading and Async Programming, we will unlock the full power of the CPU, learning how to run heavy background tasks without freezing the main application using async and await.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·