Lambda Expressions
A lambda is a tiny nameless function written on the spot, like a quick sticky note of instructions. It is handy for short jobs such as filtering a list.
In this page:
Syntax
(parameters) => expression
(parameters) => { statements; return value; }
DelegateName variable = x => x * 2;
Lambda Expressions
A lambda expression is a compact, inline, unnamed function using the => syntax, useful anywhere a delegate is expected. (x, y) => x + y is equivalent to a full method but written inline.
Lambdas are heavily used with LINQ, event handlers, and Func/Action.
Note:
A lambda with a single expression body needs no
return or braces — the expression's value is returned automatically.Example: Lambda Expressions
using System;
delegate int Transform(int x);
class Program
{
static void Main(string[] args)
{
Transform square = x => x * x;
Transform increment = x => x + 1;
Console.WriteLine(square(5));
Console.WriteLine(increment(5));
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Capturing a loop variable in a lambda and being surprised by its value later.
- Writing a lambda with wrong parameters for the delegate type, which is a compile error.
- Making a lambda long and complex, when a named method would be clearer.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: