π¦ Local Functions Capture Variables. Static Local Functions Don’t.
Local functions are great. But they capture variables. Static local functions cannot capture. Safer, more efficient.
β Capturing (Allocation)
void Process(int factor) {
int Multiply(int x) => x * factor;
// factor captured, closure allocated
}
β No Capture (No Allocation)
void Process(int factor) {
static int Multiply(int x) => x * 2;
// No capture, no allocation
}
π― Real-World Examples
// Validation logic
public bool ValidateUser(string name, int age)
{
static bool IsValidName(string n) => !string.IsNullOrEmpty(n);
static bool IsValidAge(int a) => a >= 18 && a <= 99;
return IsValidName(name) && IsValidAge(age);
}
// Recursive static local function
public static int Factorial(int n)
{
static int Fact(int x) => x <= 1 ? 1 : x * Fact(x - 1);
return Fact(n);
}
// In iterator
public static IEnumerable GetNumbers(int start, int end)
{
static IEnumerable Generate(int s, int e)
{
for (int i = s; i <= e; i++) yield return i;
}
return Generate(start, end);
}
π‘ Benefits
- No closure allocation (better performance)
- Compiler prevents accidental variable capture
- More explicit about dependencies
- Perfect for helper functions inside methods
"Local functions captured variables, caused allocations. Static local functions fixed it. Better performance, same readability."
