Delegates, Lambdas, Events and Func/Action
Passing Behavior as a Value
A delegate is a variable that holds a method. It lets you pass 'what to do' into another method.
csharp
delegate int MathOperation(int a, int b);
int Add(int a, int b) => a + b;
int Multiply(int a, int b) => a * b;
MathOperation op = Add;
Console.WriteLine(op(3, 4)); // 7
op = Multiply;
Console.WriteLine(op(3, 4)); // 12
Func, Action and Predicate
You rarely define your own delegate types. The framework gives ready-made ones:
| Type | Meaning | Example |
|---|---|---|
Action<T> | Takes input, returns nothing | Action<string> print = Console.WriteLine; |
Func<T, TResult> | Takes input, returns a value (last type is the result) | Func<int, int, int> add = (a, b) => a + b; |
Predicate<T> | Takes input, returns bool | Predicate<int> isEven = n => n % 2 == 0; |
csharp
Func<int, int, int> add = (a, b) => a + b;
Action<string> shout = text => Console.WriteLine(text.ToUpper());
Console.WriteLine(add(2, 3)); // 5
shout("hello"); // HELLO
Lambda Expressions
csharp
x => x * x // one parameter
(a, b) => a + b // two parameters
() => Console.WriteLine("Hi") // none
(int a, int b) => // statement lambda with a body
{
int sum = a + b;
return sum * 2;
}
Methods That Take Delegates
csharp
void Repeat(int times, Action action)
{
for (int i = 0; i < times; i++) action();
}
Repeat(3, () => Console.WriteLine("Hello"));
List<int> Filter(List<int> items, Func<int, bool> rule)
{
var result = new List<int>();
foreach (var item in items)
if (rule(item)) result.Add(item);
return result;
}
var big = Filter(new List<int> { 1, 50, 7, 90 }, n => n > 10); // 50, 90
Closures
A lambda can use variables from the place where it was created:
csharp
int threshold = 10;
Func<int, bool> isBig = n => n > threshold;
threshold = 100;
Console.WriteLine(isBig(50)); // False : it sees the CURRENT threshold
Events: Notify Others When Something Happens
csharp
class Thermostat
{
public event EventHandler<double>? TemperatureChanged;
private double current;
public void SetTemperature(double value)
{
current = value;
TemperatureChanged?.Invoke(this, value); // tell all subscribers
}
}
var t = new Thermostat();
t.TemperatureChanged += (sender, temp) => Console.WriteLine($"Now {temp} degrees");
t.TemperatureChanged += (sender, temp) =>
{
if (temp > 30) Console.WriteLine("Too hot!");
};
t.SetTemperature(25);
t.SetTemperature(35);
Publisher and subscriber: The class with the
event is the publisher. Code that uses += is a subscriber. The publisher does not know who listens. This is the observer pattern.
Unsubscribe: A long-living publisher keeps subscribers alive. Use
-= when a subscriber is finished, or you can leak memory.
Conclusion
Delegates hold methods, Func and Action are the ready-made versions, lambdas write them briefly and events let objects announce changes.
Quick Summary: Func returns, Action does not, lambda => is the short form, event + += subscribes.

