Skip to main content

Chapter 8: Delegates and lambda expressions

In this chapter

  • 8.1 The essence of delegates
    • What is a delegate?
    • Why do we need delegates?
    • Custom delegate types
  • 8.2 Action and Func
    • Action<T>: delegate with no return value
    • Func<T, TResult>: delegate with return value
    • Real-world example: configuration-driven behavior
    • Delegates and interfaces: how to choose?
    • Delegate type compatibility
    • Delegate parameter and return type compatibility
    • Delegate composition (multicast delegate)
  • 8.3 Lambda expressions
    • Expression lambda
    • Statement lambda
    • Simplification rules
    • Lambda natural types (C# 10)
    • Default lambda parameters (C# 12)
    • Adding attributes to lambdas (C# 10)
    • Lambda parameter modifiers (C# 14)
    • Capturing outer variables (closure)
    • Pitfall of capturing iteration variables
    • How compilers handle closures
    • Static lambda (C# 9)
    • Choice between lambda and local functions
  • 8.4 Practical applications of delegates
    • Undoable operations (Command Pattern)
    • Advanced reading: a retry executor
  • Summary
  • Exercises
    • Exercise 1: Plug-in string finder
    • Exercise 2: Chain of responsibility validator
    • Exercise 3: Fix the closure trap
  • Glossary

This chapter is not available in the free preview. Purchase the book to read the complete edition now.

Buy this book