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);With return value
Section titled “With return value”Func<int, int, int> max = (a, b) =>{ if (a > b) return a; return b;};Use in LINQ (less common but possible)
Section titled “Use in LINQ (less common but possible)”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; });Real-world usage example
Section titled “Real-world usage example”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(); };.