4. Delegates, Events & Lambdas
Evolution Timeline
C# 1.0 (2002) C# 2.0 (2005) C# 3.0 (2007)
↓ ↓ ↓
Delegates → Anonymous Methods → Lambda Expressions
(Verbose) (Better) (Best - Modern)1. Delegates (C# 1.0)
What are Delegates?
// Without delegate (direct call)
int result = Add(5, 3);
// With delegate (indirect call)
Operation operation = Add;
int result = operation(5, 3);Declaring Delegates
Instantiating Delegates
Invoking Delegates
Multicast Delegates
Delegate Variance (Covariance & Contravariance)
2. Built-in Generic Delegates
Action<T> - No Return Value (C# 3.0+)
Func<T, TResult> - With Return Value (C# 3.0+)
Predicate<T> - Returns bool (C# 2.0+)
Comparison: Action vs Func vs Predicate
Type
Parameters
Return Type
Example
3. Events (C# 1.0)
What are Events?
Event vs Delegate
EventHandler and EventHandler<T>
Basic Event Pattern
Custom EventArgs
Multiple Subscribers
Event Accessors (add/remove)
4. Anonymous Methods (C# 2.0)
Syntax
Omitting Parameters
Captured Variables (Closures)
Limitations
5. Lambda Expressions (C# 3.0+)
Expression Lambda
Statement Lambda
Type Inference
No Parameters
Discards (C# 9.0+)
Lambda Improvements (C# 10.0+)
Lambda Optional Parameters (C# 12.0+)
Evolution: Delegate → Anonymous Method → Lambda
6. Expression Trees (C# 3.0+)
What are Expression Trees?
Why Use Expression Trees?
Building Expression Trees
Examining Expression Trees
7. Closures
What are Closures?
How Closures Work
Lifetime Extension
Common Pitfall: Loop Variable Capture
8. Func and Action in Practice
Higher-Order Functions
Callbacks
Method Chaining
LINQ Integration
Common Patterns
Observer Pattern (Events)
Command Pattern (Action)
Strategy Pattern (Func)
Factory Pattern (Func)
Comparison Tables
Delegate Evolution
Feature
Delegate (C# 1.0)
Anonymous Method (C# 2.0)
Lambda (C# 3.0+)
Built-in Delegates
Delegate
Parameters
Return
Example
Event vs Delegate
Feature
Delegate
Event
Lambda Syntax Reference
Common Pitfalls
1. Event Memory Leaks
2. Loop Variable Capture (Before C# 5.0)
3. Multicast Delegate Return Values
4. Invoking Null Delegates
Best Practices
1. Use Lambda Expressions
2. Use Built-in Delegates
3. Use Events for Notifications
4. Always Unsubscribe from Events
5. Use Expression Lambda for Simple Operations
6. Be Careful with Closures
7. Use Null-Conditional for Events
Quick Reference Summary
Delegates
Events
Lambda Expressions
Closures
Common Delegates
Last updated