Skip to content

Statement lambdas

Context: Statement lambdas have a block of statements inside braces {}. They can contain multiple statements, loops, conditionals, and even local variables.

Action<int> printSquare = x =>
{
int square = x * x;
Console.WriteLine($"Square of {x} is {square}");
};
printSquare(5);
Func<int, int, int> max = (a, b) =>
{
if (a > b) return a;
return b;
};
var numbers = new List<int> { 1, 2, 3, 4 };
var evenSquares = numbers.Where(x => x % 2 == 0)
.Select(x =>
{
int square = x * x;
return square;
});

Complex event handlers: When an event handler needs multiple steps (logging, validation, processing), use a statement lambda.

Example: In WinForms, you can write button.Click += (s, e) => { MessageBox.Show("Hi"); LogClick(); };.