C# Delegates and Lambda Expressions
Use a Func predicate and make captured state’s lifetime and mutability visible.
How it works
A delegate is a typed reference to callable behaviour. Func and Action cover common result-returning and void shapes. A lambda creates callable code and may capture local variables. Captured variables are shared closure state, not necessarily frozen snapshots; later reassignment can affect the callback. Capture a separate immutable value when that is the policy you want. Stored or asynchronous callbacks also need an explicit lifetime and concurrency story.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Example
using System;
internal static class Program
{
private static void Main(string[] args)
{
int limit = 8;
int capturedLimit = limit;
Func<int, bool> fits = count => count >= 0 && count <= capturedLimit;
limit = 3;
Console.WriteLine($"Six fits snapshot: {fits(6)}");
Console.WriteLine($"Current limit: {limit}");
}
}
Expected result
Six fits snapshot: True
Current limit: 3
The rule reads capturedLimit, which this program never changes, rather than the later-updated limit. A static lambda can prevent accidental capture when no outside state is needed. Delegates make policy injection concise, but an exception raised inside the callback still follows the calling boundary’s error policy.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.