🚀 Lambdas in C#: What They Are, When to Use Them, and Real Examples
Lambdas are one of those C# features you use every day—sometimes without even thinking about them. They enable concise behavior definitions, power LINQ, and make modern C# expressive and functional.
But when should you use lambdas, and when should you avoid them?
Let’s break it down.
🧠 What Is a Lambda Expression?
A lambda expression is an inline function—a short block of code you can pass around like a value.
Basic syntax:
(parameters) => expression
Or with a body:
(parameters) =>
{
// statements
return result;
}
Example:
x => x * 2
Equivalent to:
int Double(int x) => x * 2;
🔹 Common Case Uses (With Examples) 1️⃣ LINQ Queries (Most Common Use Case)
Lambdas are the backbone of LINQ.
var activeUsers = users
.Where(u => u.IsActive)
.Select(u => u.Name)
.ToList();
Here:
- u => u.IsActive → filter condition
- u => u.Name → projection
💡 Without lambdas, LINQ would be extremely verbose.
2️⃣ Callbacks & Event Handlers
Instead of creating a separate method:
button.Click += (sender, args) =>
{
Console.WriteLine("Button clicked");
};
Perfect for:
- UI events
- Short-lived behavior
- One-off logic
3️⃣ Delegates (Func<>, Action<>, Predicate<>)
Func<T, TResult>
Func<int, int> square = x => x * x;
Console.WriteLine(square(4)); // 16
Action<T>
Action<string> log = msg => Console.WriteLine(msg);
log("Hello");
Predicate<T>
Predicate<int> isEven = x => x % 2 == 0;
4️⃣ Configuration & Fluent APIs
Very common in modern APIs:
services.AddHttpClient("api", client =>
{
client.BaseAddress = new Uri("https://api.example.com");
});
Or:
options.Configure(o => o.EnableCaching = true);
Lambdas make configuration readable and localized.
5️⃣ Sorting, Filtering, and Comparison
products.Sort((a, b) => a.Price.CompareTo(b.Price));
Or:
var ordered = products.OrderBy(p => p.Price);
No need for a full IComparer<T> implementation.
6️⃣ Encapsulating Behavior (Strategy Lite)
Instead of multiple if blocks:
Func<int, int> operation = mode switch
{
1 => x => x + 10,
2 => x => x * 2,
_ => x => x
};
This is a lightweight strategy pattern using lambdas.
⚠️ When NOT to Use Lambdas
Lambdas are powerful—but not always the right tool.
❌ Avoid lambdas when:
- The logic is complex or long
- The lambda spans many lines
- The intent is unclear without comments
- You need reuse or unit testing
Bad example:
items.Where(x =>
{
if (x.A > 10 && x.B < 5 && CheckSomething(x))
{
DoSideEffect();
return true;
}
return false;
});
✅ Better:
items.Where(IsValidItem);
bool IsValidItem(Item x)
{
// clear, testable, reusable
}
🧬 Lambdas vs Local Functions
Local function:
int Add(int a, int b) => a + b;
Lambda:
Func<int, int, int> add = (a, b) => a + b;
Rule of thumb:
- Lambda → behavior passed around
- Local function → helper logic
🧪 Expression Lambdas vs Statement Lambdas
Expression:
x => x * 2
Statement:
x =>
{
var result = x * 2;
return result;
}
LINQ providers (EF Core, etc.) often require expression lambdas, not statements.
🎯 Why Lambdas Matter in Modern C#
Lambdas enable:
- Functional-style programming
- Clean LINQ pipelines
- Declarative configuration
- Less boilerplate
- More expressive APIs
They are one of the pillars of modern C#.
#csharp #dotnet #softwareengineering #cleanCode