Glossary / Lambdas

Lambdas

A lambda expression is an inline function expression that can be converted to a delegate or, in certain contexts, an expression tree. Lambdas provide concise callbacks and query predicates while retaining static typing and lexical capture of variables.

Syntax, inference, and capture

Func<int, bool> isEven = n => n % 2 == 0;

Parameter types are often inferred from the target delegate; explicitly typed lambdas can resolve overloads or improve clarity. Expression lambdas contain one expression; statement lambdas use a block. Captured local variables are hoisted into closure state so their lifetime can outlast the method. Captured variables are captured by reference-like shared storage, not snapshotted values; loop-capture behavior depends on variable declaration scope (modern foreach creates per-iteration variables, while classic for loop variable capture is shared).

Lambdas can be static to prohibit captures, improving clarity and sometimes avoiding closure allocations. C# 10+ supports natural function types in some contexts; C# 14 includes modifiers on simple lambda parameters. Async lambdas targeting Action become async void, which is usually unsafe for operations requiring await/error propagation.

Engineering guidance

Keep lambdas short; extract named methods when logic is substantial or reused. Be mindful of captured object lifetimes and thread-safety. Prefer static lambdas when no capture is intended. Avoid async-void callbacks except APIs that require void handlers.

Interview questions

  1. What can a lambda convert to? A compatible delegate or expression tree where the target context allows.
  2. How are captured variables handled? Compiler-generated closure state keeps them available, often extending lifetime.
  3. What does static lambda guarantee? It cannot capture local or instance state.
  4. Why are async lambdas to Action problematic? They become async void and cannot be awaited by the caller.
  5. When extract a named method? For complex, reusable, testable, or diagnostically important behavior.

References