๐Ÿ  VisualStudioTutor.com  ยท  C# Tutorial Home  ยท  C# Lesson 11 of 40
Lesson 11 of 40 Core C# Intermediate โฑ 35 min

Delegates, Events & Lambdas

Unlock functional programming in C# โ€” delegates as first-class functions, Func/Action, lambda expressions, closures, and the event system.

Part 1: Func, Action & Predicate

// Func<TInput, TOutput>
Func<int, int, int> add = (a, b) => a + b;

// Action โ€” void return
Action<string> print = s => Console.WriteLine(s);

// Predicate โ€” returns bool
Predicate<int> isEven = n => n % 2 == 0;

add(3, 4); // 7
print("Hi"); // Hi
isEven(6); // true

Part 2: Lambda Closures

int multiplier = 3; // Captured by closure
Func<int, int> triple = x => x * multiplier;
multiplier = 5; // โš ๏ธ Changes captured value!
Console.WriteLine(triple(4)); // 20, not 12!

// Fix: capture a local copy
int m = multiplier;
Func<int, int> safe = x => x * m;

Part 3: Custom Events

public class Button
{
    public event EventHandler<ClickEventArgs>? Clicked;

    public void Click() =>
        Clicked?.Invoke(this, new ClickEventArgs());
}

var btn = new Button();
btn.Clicked += (s, e) => Console.WriteLine("Clicked!");

Part 4: Higher-Order Functions

// Pass functions as parameters
static IEnumerable<T> Filter<T>(IEnumerable<T> items, Func<T, bool> predicate)
    => items.Where(predicate);

// Return functions from functions
static Func<int, int> Multiplier(int factor) => x => x * factor;
var double = Multiplier(2); // Partially applied

C# in Visual Studio 2026

๐Ÿ“˜ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition