Local Functions vs Lambdas
Choose between local functions and lambdas.
Local Functions vs Lambdas
Both local functions and lambdas let you define small functions inside a method. They overlap a lot, but differ in syntax, capabilities, and performance. Choosing the right one keeps code clear and efficient.
Two Ways to Write a Helper
Here the same squaring helper is written both as a local function and as a lambda assigned to a delegate. Both produce the same result.
using System;
public class Program
{
public static void Main()
{
int SquareFn(int n) => n * n; // local function
Func<int, int> squareLambda = n => n * n; // lambda
Console.WriteLine(SquareFn(4));
Console.WriteLine(squareLambda(4));
}
}All lessons in this course
- Declaring Local Functions
- Closures and Captured Variables
- Static Local Functions
- Local Functions vs Lambdas