Lambda expressions
A lambda expression is an anonymous function. It gives a concise syntax for creating a delegateDelegatesA type-safe function pointer, so a method can be passed around like any other value.Opens in a new tab or an expression tree. It is a more compact way to write inline functions that would otherwise need a full method definition.
Three ways to write the same thing
All three do exactly the same thing. The lambda just strips away the ceremony.
// 1. A regular named methodbool IsEven(int n) { return n % 2 == 0; }Func<int, bool> check1 = IsEven; // 2. An anonymous method (older C# style)Func<int, bool> check2 = delegate (int n) { return n % 2 == 0; }; // 3. A lambda expression (modern, shortest)Func<int, bool> check3 = n => n % 2 == 0;The shape of a lambda
It reads input => output, and => is read as “goes to”. The same shape covers no input, a typed input, and several inputs with a block body.
n => n % 2 == 0() => Console.WriteLine("Hi")(int n) => n % 2 == 0(a, b) => { return ...; }In code
The first one is the kind you see all the time with LINQ methods: the lambda on line 3 is num => num % 2 == 0. The second, on line 6, is a lambda assigned to a delegate.
int[] numbers = { 1, 2, 3, 4, 5, 6 };// Lambda expression: num => num % 2 == 0IEnumerable<int> evenNumbers = numbers.Where(num => num % 2 == 0); // Lambda expression for a delegate:Func<int, int, int> add = (x, y) => x + y;// int sum = add(5, 3); // sum is 8Where it matters
Lambdas make code much more readable and concise, especially with LINQ, event handlersEventsHow a class tells other classes that something happened, without knowing who is listening.Opens in a new tab and asynchronous operations. They are a cornerstone of functional programming idioms in C#.
How a lambda gets passed into a LINQ method is in the LINQ noteLINQ: query syntax and method syntaxOne SQL-like way to query many kinds of data, written in two equivalent forms.Opens in a new tab.
Sources
- Write LINQ queries, C#, Microsoft Learn · accessed May 16, 2025