Lambda Expressions: The Shortcut

Lambda Expressions: The Shortcut in C#: A company policy is a document. It has a title, a page in the handbook, a review date, and everyone can look it up by…

The Analogy: The Sticky Note

A company policy is a document. It has a title, a page in the handbook, a review date, and everyone can look it up by name. That is a method: declared, named, reusable, findable.

Sometimes you do not need a policy. You need to hand someone a sticky note that says "sort these by length" and have them get on with it. The note has no title, nobody files it, and when the job is done it goes in the bin. That is a lambda: a small piece of behaviour written exactly where it is used and passed to whoever needs it.

Every LINQ call in the last lesson was a sticky note. p => p.Price < 20m is a whole method — takes a product, returns a bool — that was never worth naming. The trick lambdas pull off is that behaviour becomes something you can put in a variable, pass as an argument and return from a method, just like an int.


Syntax or Core Structure

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        Func<int, int> square = x => x * x;              // one in, one out
        Func<int, int, int> add = (a, b) => a + b;        // two in, one out
        Action<string> shout = text => Console.WriteLine(text.ToUpper());   // in, nothing out
        Predicate<int> isEven = n => n % 2 == 0;          // in, bool out
        Func<double> roll = () => 4.5;                   // nothing in, one out

        Console.WriteLine($"square 7 = {square(7)}, add 3+4 = {add(3, 4)}");
        shout("lambdas");
        Console.WriteLine($"8 even? {isEven(8)}, roll {roll():F1}");

        Func<int, int, int> multiply = (int a, int b) =>  // explicit types, block body
        {
            int result = a * b;
            return result;                               // block bodies need 'return'
        };
        Console.WriteLine($"multiply 6x7 = {multiply(6, 7)}");

        int offset = 10;                                 // captured, not copied
        Func<int, int> shift = x => x + offset;
        Console.WriteLine($"shift 5 = {shift(5)}");
        offset = 100;
        Console.WriteLine($"shift 5 again = {shift(5)}");

        List<string> names = new() { "grace", "ada", "alan", "linus" };
        var sorted = names.OrderBy(n => n.Length).ThenBy(n => n);

        Console.WriteLine($"by length: {string.Join(", ", sorted)}");
        Console.WriteLine($"initials: {string.Join("", names.Select(n => n[0]))}");
    }
}

Output:

square 7 = 49, add 3+4 = 7
LAMBDAS
8 even? True, roll 4.5
multiply 6x7 = 42
shift 5 = 15
shift 5 again = 105
by length: ada, alan, grace, linus
initials: gaal

Stop at those two shift lines. The lambda did not copy offset when it was written; it kept a live connection to the variable, so changing offset afterwards changed what shift computes. That is a closure, and it is the single most consequential thing in this lesson.


Technical Depth: Delegates, Closures and the Arrow's Two Jobs

A lambda is a delegate, and a delegate is a type

Func and Action are not magic; they are delegate types — a type whose values are methods. You can declare your own, and the framework's generic ones exist so that you rarely need to:

delegate int Transform(int x);           // a custom delegate type
Transform t = x => x + 1;                // a lambda fits it
Transform u = Increment;                 // so does a method group
static int Increment(int x) => x + 1;
TypeShapeUse
Action() => voiddo something, return nothing
Action<T1..T16>(T1..) => voidsame, with parameters
Func<TResult>() => TResultproduce a value
Func<T1..T16, TResult>(T1..) => TResultlast type parameter is the return type
Predicate<T>T => boola test; Func<T,bool> in all but name
Comparison<T>(T, T) => intwhat List<T>.Sort wants

The "last one is the return type" rule catches everyone once: Func<int, string> takes an int and returns a string, not the other way round.

The forms a lambda can take

x => x * 2                        // inferred type, expression body
(x, y) => x + y                   // several parameters
(int x) => x * 2                  // explicit type when inference fails
() => Console.WriteLine("hi")     // no parameters
x => { Log(x); return x * 2; }    // block body
(x, _) => x                       // discard a parameter you must accept but ignore
static x => x * 2                 // C# 9: cannot capture anything (see below)
(int x, int step = 1) => x + step // C# 12: default parameter values
async x => await LoadAsync(x)     // an async lambda

Since C# 10 a lambda even has a natural type, so var f = (int x) => x * 2; compiles and f is a Func<int,int>.

Closures, and the loop trap

Captured variables are lifted into a compiler-generated class, which is why they outlive the method that declared them. It is also why this classic goes wrong:

var actions = new List<Action>();
for (int i = 0; i < 3; i++)
    actions.Add(() => Console.Write(i));      // all three share ONE i

foreach (var a in actions) a();               // prints 333, not 012

There is one i for the whole loop, and by the time the delegates run it is 3... except the loop exited when i hit 3, so every note reads "3". The fix is a fresh variable per iteration:

for (int i = 0; i < 3; i++)
{
    int copy = i;
    actions.Add(() => Console.Write(copy));   // prints 012
}

A foreach variable is already per-iteration (since C# 5), so foreach does not have this bug. A for counter does.

The cost, and static lambdas

A lambda that captures nothing is cached and effectively free. A lambda that captures allocates a closure object every time the enclosing method runs — invisible in a report, expensive in a per-frame loop. static (C# 9) makes accidental capture a compile error:

int limit = 10;
Func<int, bool> a = x => x < limit;          // allocates a closure holding 'limit'
Func<int, bool> b = static x => x < 10;      // captures nothing; CS8820 if you try

Lambda, local function, or method?

LambdaLocal functionPrivate method
Has a nameNoYesYes
Can be passed as a valueYesYes (with a conversion)Yes (method group)
Can be recursiveAwkwardlyYesYes
Allocates when capturingYes, a closure objectOften notn/a
Best forone-line arguments to LINQa helper used twice inside one methodanything reused or worth testing

If a lambda grows past three or four lines, it has stopped being a sticky note. Promote it.

Method group conversion

When a lambda does nothing but forward its arguments, drop it:

names.Select(n => Normalize(n));      // works
names.Select(Normalize);              // clearer, and one less delegate shape to infer
words.Where(string.IsNullOrEmpty);

The same lambda can be code or data

Func<Order, bool> code = o => o.Total > 100m;                  // compiled: just call it
Expression<Func<Order, bool>> data = o => o.Total > 100m;      // a tree you can inspect

The second form is how Entity Framework reads your intent and emits WHERE Total > 100 — the IQueryable story from the LINQ lesson. Identical source text, two entirely different things.

One arrow, two features

=> also introduces an expression-bodied member, which is not a lambda at all:

public double Area => Math.PI * r * r;         // expression-bodied property
public void Log(string m) => Console.WriteLine(m);   // expression-bodied method
Func<int,int> f = x => x + 1;                  // an actual lambda

Same punctuation, different jobs. And a caution for events: you cannot unsubscribe an anonymous lambda, because you no longer have a reference to it. button.Click += (s, e) => ... is permanent; store the delegate in a variable if you will ever need -=.


Real World Example: Rules You Can Add Without Recompiling the Checker

Validation is where storing behaviour in a variable earns its keep. Validator below knows nothing about orders — it holds a list of tests, each one a lambda, and reports which ones failed.

using System;
using System.Collections.Generic;
using System.Linq;

record Order(string Id, string Customer, decimal Total, int Items, string Country);

class Validator
{
    private readonly List<(string Rule, Func<Order, bool> Passes, string Message)> rules = new();

    public Validator Add(string rule, Func<Order, bool> passes, string message)
    {
        rules.Add((rule, passes, message));
        return this;                                    // fluent: Add(...).Add(...)
    }

    public IReadOnlyList<string> Check(Order order) =>
        rules.Where(r => !r.Passes(order))              // a lambda calling a lambda
             .Select(r => $"{r.Rule}: {r.Message}")
             .ToList();
}

class Program
{
    static void Main()
    {
        var validator = new Validator()
            .Add("total",   o => o.Total > 0m,          "total must be positive")
            .Add("items",   o => o.Items >= 1,          "at least one item required")
            .Add("cap",     o => o.Total <= 5000m,      "over the 5000 approval cap")
            .Add("country", o => o.Country.Length == 2, "country must be a 2-letter code");

        Func<Order, decimal> discount = o =>
              o.Total >= 1000m ? 0.10m
            : o.Total >= 500m  ? 0.05m
            : 0m;

        Order[] orders =
        {
            new("A-1", "ada",   1200m,  3, "GB"),
            new("A-2", "grace",  620m,  0, "GB"),
            new("A-3", "alan",  6400m, 12, "USA"),
            new("A-4", "linus",   -5m,  1, "FI")
        };

        foreach (Order o in orders)
        {
            IReadOnlyList<string> problems = validator.Check(o);

            if (problems.Count == 0)
            {
                decimal rate = discount(o);
                Console.WriteLine($"{o.Id} ok      {o.Total,8:F2} -{rate * 100m:F0}% -> {o.Total * (1m - rate),8:F2}");
            }
            else
            {
                Console.WriteLine($"{o.Id} REJECT  {o.Total,8:F2}");
                foreach (string p in problems)
                    Console.WriteLine($"        {p}");
            }
        }

        Console.WriteLine($"{orders.Count(o => validator.Check(o).Count == 0)}/{orders.Length} accepted");
    }
}

Output:

A-1 ok       1200.00 -10% ->  1080.00
A-2 REJECT    620.00
        items: at least one item required
A-3 REJECT   6400.00
        cap: over the 5000 approval cap
        country: country must be a 2-letter code
A-4 REJECT     -5.00
        total: total must be positive
1/4 accepted

Adding a fifth rule is one .Add(...) line — no if in Check, no subclass, no interface. A-3 reports both its problems because Check filters rather than returning at the first failure, which is what a user filling in a form actually wants. And discount shows the other half of the idea: a small pricing decision living in a variable, replaceable per country or per campaign without touching the loop that applies it.


Common Mistakes

  1. Capturing a for loop counter. All the delegates share one variable and see its final value. Copy it into a loop-local first.
  2. Assuming a captured variable is a snapshot. It is a live reference; change it afterwards and every lambda holding it changes behaviour.
  3. Getting Func's type order backwards. Func<string, int> takes a string and returns an int. The return type is always last.
  4. Forgetting return in a block-bodied lambda. x => { x * 2; } does not compile; x => x * 2 and x => { return x * 2; } both do.
  5. Letting a lambda grow to twenty lines inside a LINQ chain. It is now an untestable, unnamed method in the middle of a query. Promote it to a local function or a method.
  6. Subscribing an anonymous lambda to an event you will need to detach. -= needs the same delegate instance; keep it in a variable.
  7. Allocating closures in a hot loop. Each capture is an object. Hoist the lambda out of the loop, or mark it static so the compiler tells you when you capture by accident.
  8. Mutating captured state from a LINQ lambda. Deferred execution means you cannot say when — or how often — it will run.

Best Practices

  • Keep lambdas to one expression where you can. If it needs braces and more than a couple of statements, give it a name.
  • Prefer a method group over a forwarding lambda: Select(Normalize), not Select(x => Normalize(x)).
  • Use static lambdas when nothing should be captured — it documents the intent and the compiler enforces it.
  • Store behaviour in Func/Action fields when the variation is data, not hierarchy: a rule list beats four subclasses that each override one method.
  • Name the delegate parameters meaningfully: (order, index) => reads better than (o, i) => in anything longer than a filter.
  • Reach for Expression<Func<...>> only when a provider needs to inspect the query — Entity Framework, mapping libraries. Everywhere else, Func is faster and simpler.
  • Copy loop variables before capturing them, every time, without thinking about whether this particular loop is safe.
  • Use local functions for recursion and shared helpers inside one method, lambdas for arguments you pass out.

Practice Exercises

  1. Declare four delegates in one Main: a Func<double, double> returning the square root, an Action<string, int> that prints a name repeated N times, a Predicate<string> testing for a vowel start, and a Func<int, int, int> returning the larger value. Call each one and print the result.
  2. Write static Func<decimal, decimal> MakeTaxCalculator(decimal rate) that returns a lambda closing over rate. Build calculators for 20% and 5%, apply both to 250.00, and print the results — then explain in a comment where rate is actually stored.
  3. Reproduce the loop-capture bug: build a List<Action> inside a for loop that prints the counter, run them all, and show it printing the wrong thing. Then fix it with a loop-local copy and show the correct output. Repeat with a foreach over an array and note that no fix is needed.
  4. Extend the Validator: add Validator AddWarning(...) so rules are either errors or warnings, and a Func<Order, string> "formatter" field the caller supplies so Check output can be plain text or CSV. Run the same four orders through with both formatters, and add a comment on why storing the formatter as a delegate is preferable to a bool useCsv parameter.