Methods, Lambdas, and Local Functions in C# – What's the Difference? When learning C#, you’ll often hear about methods, lambdas, and local functions. While they all let you encapsulate code logic, they serve slightly different purposes and behave differently in a few key areas.
Methods
Methods are the standard way to encapsulate reusable logic in C#. They’re declared as part of a class or struct, can take parameters, return values, and have access modifiers like public
, private
, etc.
public int Add(int a, int b)
{
return a + b;
}
Methods are always declared at the class level, not inside other methods.
Lambdas
Lambdas are anonymous functions often used as inline expressions or to define delegates. They’re compact, functional-style, and don’t require a name.
Func<int, int, int> add = (a, b) => a + b;
Lambdas are especially useful in LINQ queries or as callbacks:
var evens = numbers.Where(n => n % 2 == 0);
Lambdas can capture variables from their surrounding scope (called closures), which makes them powerful—but also a bit tricky if you don’t understand scope lifetimes.
Local functions
Local functions are named methods declared inside another method. They’re useful for organizing helper logic that doesn’t need to be exposed outside the parent method.
public void Process()
{
int Square(int x) => x * x;
Console.WriteLine(Square(4));
}
Local functions are type-safe, support recursion, and benefit from compile-time checking—advantages over lambdas when the logic is more complex or used multiple times within the method.
Key differences
Feature | Method | Lambda | Local Function |
---|---|---|---|
Named | Yes | No | Yes |
Scope | Class level | Variable scope | Inside method |
Captures context | No | Yes (closures) | Yes |
Recursion | Yes | No (unless assigned) | Yes |
Async/await | Yes | Yes | Yes |
When to use what?
- Use methods when the logic is reused or part of the class’s responsibility.
- Use lambdas for short, inline logic—especially when working with LINQ or events.
- Use local functions for keeping related logic private and organized within a single method.
Each has its place—understanding their differences helps write cleaner, more maintainable C# code.