In C#, how does an expression lambda differ from a statement lambda, and where does the compiler get a lambda's parameter types?
answer
- what follows the arrow
- one expression vs a block
- return on every path
- the target delegate supplies the types
basics
~20 sAn expression lambda's body is a single expression whose value is the result; a statement lambda's body is a block that must return explicitly on every path. Untyped parameters take their types from the delegate the lambda is converted to.
solid answer
~40 s`amount => amount > 100m` is an **expression lambda**: the body is one expression and its value is what the delegate returns. `amount => { if (amount > 250m) return "priority"; return "standard"; }` is a **statement lambda**: a block of statements that needs `return` on every path when the delegate returns a value, or the compiler reports CS1643. Parameters can be written without types because the compiler takes them from the target delegate, so passing a lambda to `List<decimal>.FindAll` makes `o` a `decimal`. Types are all explicit or all implicit (CS0748), and `_` discards unused inputs. With no target at all, `var twice = x => x * 2;` fails with CS8917 because nothing says what `x` is.
code
csharp · 19 linesvar orders = new List<decimal> { 40m, 120m, 300m };
// Expression lambda: the body is one expression, and its value is the result.
Func<decimal, bool> isLarge = amount => amount > 100m;
// Statement lambda: a block that must return on every path.
Func<decimal, string> describe = amount =>
{
if (amount > 250m) return "priority";
return amount > 100m ? "standard" : "small";
};
// Parameter types come from the target delegate; discards ignore inputs.
Func<decimal, decimal, decimal> pickFirst = (first, _) => first;
Console.WriteLine(orders.FindAll(o => o > 100m).Count); // 2
Console.WriteLine(isLarge(120m)); // True
Console.WriteLine(describe(300m)); // priority
Console.WriteLine(pickFirst(1m, 2m)); // 1go deeper
Recall the two body shapes and when each needs a return statement, and be able to write a lambda for List<T>.FindAll or a Func without looking it up.
Explain that parameter types come from the target delegate, why var with untyped parameters fails, and what CS1643 means in a statement lambda.
Spot in review where a statement lambda hides logic that deserves a named method, and know that only expression lambdas can become expression trees for query providers.
Have a view on house style: when a multi-line statement lambda in a call chain should become a named method so it can be tested and read on its own.
## Two shapes of the same feature A **lambda expression** in C# is an anonymous function written with the `=>` operator: parameters on the left, a body on the right. The compiler converts it to a **delegate** (a `Func<...>`, an `Action<...>`, a `Predicate<T>` or your own delegate type) whose `Invoke` method runs the body. The body comes in two shapes: | Shape | Body | Result | |---|---|---| | **Expression lambda** | one expression, no braces | the expression's value is returned | | **Statement lambda** | a `{ ... }` block of statements | a `return` statement supplies the value | An expression lambda such as `amount => amount > 100m` is the common form for filters and projections. A statement lambda is used when the logic needs several steps, local variables, `if` statements or loops. ## Expression lambdas - The body is a single expression, and its value becomes the return value: `o => o > 100m` returns `bool`. - When the target delegate returns `void` (an `Action<T>`), the body may be a method call or another expression that is legal as a statement, such as `name => Console.WriteLine(name)`, and its value, if any, is discarded. - An expression lambda cannot contain statements such as `if`, `for` or a local declaration; use the conditional operator or switch to a statement lambda. ## Statement lambdas A statement lambda is a small method body. When the target returns a value, **every code path must end in `return`**. This fails: ```csharp Func<int, string> describe = x => { if (x > 0) return "positive"; }; ``` with **CS1643**: "Not all code paths return a value in lambda expression of type 'Func<int, string>'". Writing a bare expression inside the braces is also wrong: `x => { x > 0 ? "positive" : "other"; }` reports **CS0201**, because a conditional expression on its own is not a valid statement. A `return` inside a lambda returns from the lambda only, never from the enclosing method, and `break` or `continue` cannot jump out of the lambda body. ## Where parameter types come from Most lambdas are written with **implicitly typed parameters**, and the compiler fills the types in from the delegate the lambda is converted to: 1. Passing `o => o > 100m` to `List<decimal>.FindAll(Predicate<decimal>)` makes `o` a `decimal`. 2. Assigning `(first, _) => first` to a `Func<decimal, decimal, decimal>` makes both parameters `decimal`; the `_` **discard** marks an input the body ignores. 3. Writing the types yourself, `(decimal first, decimal second) => first`, is also legal, but a parameter list is **all explicit or all implicit**; mixing them reports **CS0748**. Parentheses are optional only for a single implicitly typed parameter: `x => x * 2`. No parameters is `() => ...`; two or more always need parentheses. When there is no target type, the compiler has nothing to infer from. `var twice = x => x * 2;` fails with **CS8917**, "The delegate type could not be inferred". Giving the parameter a type, `var twice = (int x) => x * 2;`, compiles because such a lambda has a *natural type*; how the compiler picks that delegate type is covered with delegate types. ## Choosing between the two shapes The two shapes compile to the same kind of delegate, so the choice is about readability: - use an **expression lambda** when the logic is one test or one projection, as in `orders.FindAll(o => o > 100m)`; - use a **statement lambda** when you need a local variable, several branches or a loop, and keep it short; - move a statement lambda that grows past a few lines into a **named method** and pass the method group instead, so it gets a name, its own tests and a readable stack trace. A statement lambda that only returns one expression, `o => { return o > 100m; }`, is legal but only adds braces and a keyword to the expression form. ## How interviewers probe it - They show a statement lambda with a missing `return` path and ask for the compiler error. - They ask why `var f = x => x;` does not compile when `Func<int, int> f = x => x;` does. - They ask what `return` inside a lambda passed to a loop helper does to the outer method: nothing; it ends only that call of the lambda. - They ask which shape LINQ providers can translate: only an expression lambda can become an expression tree, and a statement body reports **CS0834**; the trees themselves are covered with LINQ. ## Common mistakes - Thinking an expression lambda needs a `return` keyword. - Thinking a statement lambda returns its last expression automatically. - Expecting `var` to work with untyped parameters. - Mixing `(decimal first, second)` in one parameter list.
- In C#, what does a return statement inside a lambda passed to List<T>.ForEach do to the enclosing method?Nothing. A `return` inside a lambda ends that invocation of the lambda only; the enclosing method keeps running, and `ForEach` moves on to the next element. To stop the outer method you need an ordinary `foreach` loop, where `return` and `break` act on the method and the loop.
- In C#, can a lambda declare its own local variables, and are they visible after it?A statement lambda may declare locals inside its block, and they are visible only inside that body; the enclosing method cannot see them. An expression lambda has no block, so it cannot declare locals except through pattern variables or `out var` inside the expression.
- Says an expression lambda needs an explicit return keyword.
- Claims a statement lambda returns its last expression automatically.
- Believes var f = x => x * 2; compiles because the compiler guesses int.
- Thinks return inside a lambda exits the enclosing method.
- Mixes typed and untyped parameters in one lambda parameter list.