Chapter 18: Delegates, Events, and Lambda Expressions

1. What is a Delegate? (Super Simple Analogy)

Think of a delegate like a phone number or a remote control pointer:

  • You have a method (the person who does the work)
  • You create a delegate (the phone number) that points to that method
  • You can call the delegate → it calls the method (even if you don’t know the method name anymore)
  • You can change what the delegate points to → switch who answers the phone!

In C#, a delegate is a type-safe function pointer – it lets you pass methods as parameters, store them in variables, and call them later.

2. Defining and Using a Basic Delegate

Syntax:

C#

Output:

text

3. Events and Event Handlers – The Real Power of Delegates

An event is a special kind of delegate that allows other classes to subscribe (listen) to something happening.

Analogy: A button has a Click event. Any number of methods can subscribe to it (like ShowMessage, SaveData, PlaySound). When the button is clicked → all subscribed methods are called automatically!

Syntax:

C#

Output:

text

4. Anonymous Methods and Lambda Expressions (=>) – Modern & Super Clean

Anonymous method (old style – C# 2.0):

C#

Lambda expression (C# 3.0+ – the modern way – short & beautiful):

C#

Very common real-world example:

C#

5. Func, Action, Predicate – Built-in Generic Delegates

C# provides ready-made generic delegates so you don’t have to define your own every time.

Delegate Signature Use Case Example
Action void (params) Methods that do something Action<string> log = msg => Console.WriteLine(msg);
Action<T> void (T) One parameter Action<int> print = n => Console.WriteLine(n);
Func<T> T () Returns value, no input Func<DateTime> now = () => DateTime.Now;
Func<T1,T2, TResult> TResult (T1,T2) Most common – returns result Func<int,int,int> add = (a,b) => a+b;
Predicate<T> bool (T) Returns true/false (test condition) Predicate<int> isEven = n => n % 2 == 0;

Real example – Using built-in delegates

C#

Mini-Project: Event-Driven Notification System

C#

Output:

text

Summary – What We Learned Today

  • Delegate → type-safe function pointer (pass methods around)
  • Event → special delegate for publish-subscribe pattern
  • Lambda expressions (=>) → short, anonymous methods
  • Func, Action, Predicate → built-in generics for common signatures
  • Multicast → one delegate/event can call multiple methods
  • Used everywhere: LINQ, events, async/await, callbacks, Unity events…

Your Homework (Super Fun & Practical!)

  1. Create a new console project called DelegatesAndEvents
  2. Create a class TemperatureSensor with:
    • Event TemperatureChanged (use Action<double>)
    • Method ChangeTemperature(double newTemp) that raises the event
  3. Create 3 subscribers:
    • Display → shows current temperature
    • Alarm → beeps if > 40°C
    • Logger → logs to console with timestamp
  4. In Program.cs: Subscribe all 3, change temperature a few times, and see the magic!

Next lesson: LINQ (Language Integrated Query) – we’re going to learn how to query, filter, sort, and transform collections like magic!

You’re doing absolutely fantastic! 🎉 Any part confusing? Want more examples with multicast events or lambdas? Just tell me — I’m right here for you! 💙

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *