How to require a static lambda or delegate in C#
C# has no parameter modifier that forces callers to pass a static lambda, and Delegate.Method.IsStatic is false for a static lambda. Three options that actually work on .NET 11: a function pointer, a runtime check on Delegate.Target, and a small Roslyn analyzer behind a [RequireStatic] attribute.
This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process
Short answer: C# 15 on .NET 11 has no way to declare “this Func<T> parameter only accepts static lambdas”. The static modifier on a lambda (C# 9) is a promise the caller makes, it is not visible in the delegate type, and it does not even make the emitted method static: (static () => 42).Method.IsStatic is false. If you need a compile-time guarantee, take a function pointer (delegate*<P, R>), which only binds to static methods, or ship a Roslyn analyzer that rejects non-static lambdas passed to a parameter marked [RequireStatic]. If a runtime check is enough, walk GetInvocationList() and accept a delegate only when its Target is null or is the compiler’s stateless <>c singleton. All three are shown below, built and run on SDK 11.0.100.
This question comes up when someone writes a “run this on another thread, then hand the result back” helper, wants the work delegate to be free of captured mutable state, and discovers that neither the type system nor reflection makes the obvious check work. It was asked on Stack Overflow as How can I require a delegate/lambda to be static?, with an accepted answer that sketches an analyzer. This post measures what the runtime actually sees for every kind of delegate, which is what both the runtime check and the analyzer have to be built around.
Why Delegate.Method.IsStatic gives the wrong answer for lambdas
The intuitive runtime check is del.Method.IsStatic || del.Target is null. It fails because of how Roslyn compiles lambdas. A lambda that captures nothing is not emitted as a static method. It becomes an instance method on a nested compiler-generated class called <>c, and the delegate is bound to a singleton instance of that class stored in <>c.<>9. Roslyn does this because invoking a delegate bound to an instance method is cheaper than invoking one bound to a static method (the static case goes through a shuffle thunk that drops the unused this slot).
Adding static to the lambda changes nothing in the output. The static anonymous functions spec says so explicitly: it makes no guarantee that a static anonymous function is emitted as a static method, and removing the modifier from a valid program does not change its meaning. The modifier only makes the compiler reject captures of locals, parameters and this inside the lambda body.
Here is what the runtime reports for every common way to produce a Func<int>. The program is a .NET 11 file-based app:
// .NET 11 (SDK 11.0.100), C# 15. Run with: dotnet run -c Release probe.cs
#:property PublishAot=false
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
var demo = new Demo();
int fortyTwo = 42;
Show("static method group", (Func<int>)Demo.StaticFunction);
Show("instance method group", (Func<int>)demo.InstanceFunction);
Show("static lambda", static () => 42);
Show("non-capturing lambda", () => 42);
Show("lambda capturing local", () => fortyTwo);
Show("lambda capturing this", demo.MakeThisCapturingLambda());
Show("static local function", (Func<int>)StaticLocal);
Show("non-capturing local function", (Func<int>)PlainLocal);
Show("extension method group", (Func<int>)"abc".Twice);
Expression<Func<int>> expr = () => 42;
Show("compiled expression tree", expr.Compile());
Show("multicast static+capturing", (Func<int>)Demo.StaticFunction + (() => fortyTwo));
static int StaticLocal() => 7;
int PlainLocal() => 7;
static void Show(string label, Delegate d)
{
var t = d.Target;
var fields = t?.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? [];
Console.WriteLine($"{label,-30} IsStatic={d.Method.IsStatic,-5} " +
$"Target={(t is null ? "null" : t.GetType().FullName),-45} instFields={fields.Length} " +
$"count={d.GetInvocationList().Length} => {Guard.CapturesNoState(d)}");
}
class Demo
{
int _value = 1;
public static int StaticFunction() => 1;
public int InstanceFunction() => _value;
public Func<int> MakeThisCapturingLambda() => () => _value;
}
static class Ext
{
public static int Twice(this string s) => s.Length * 2;
}
Guard.CapturesNoState is the runtime check from the next section; append that class to the file to run it. The output on macOS arm64, .NET 11.0.0, Release:
static method group IsStatic=True Target=null instFields=0 count=1 => True
instance method group IsStatic=False Target=Demo instFields=1 count=1 => False
static lambda IsStatic=False Target=Program+<>c instFields=0 count=1 => True
non-capturing lambda IsStatic=False Target=Program+<>c instFields=0 count=1 => True
lambda capturing local IsStatic=False Target=Program+<>c__DisplayClass0_0 instFields=1 count=1 => False
lambda capturing this IsStatic=False Target=Demo instFields=1 count=1 => False
static local function IsStatic=True Target=null instFields=0 count=1 => True
non-capturing local function IsStatic=True Target=null instFields=0 count=1 => True
extension method group IsStatic=True Target=System.String instFields=2 count=1 => False
compiled expression tree IsStatic=True Target=System.Runtime.CompilerServices.Closure instFields=2 count=1 => False
multicast static+capturing IsStatic=False Target=Program+<>c__DisplayClass0_0 instFields=1 count=2 => False
Four rows break the naive check:
static lambda:IsStaticisFalseandTargetis not null. A check on either property rejects exactly the delegate you wanted to accept.extension method group:"abc".Twicebinds a static method with its first argument closed over, soIsStaticisTruewhileTargetis the string"abc". AnIsStatic-only check accepts a delegate that carries state.compiled expression tree:IsStaticisTrue(the compiledDynamicMethodis static), but the target is aSystem.Runtime.CompilerServices.Closureobject. Again,IsStaticalone lets it through.multicast:Delegate.Targetreturns the target of the last instance method in the invocation list, andMethoddescribes only the last entry too. A multicast delegate has to be checked entry by entry.
Local functions behave differently from lambdas: a local function that captures nothing is emitted as a real static method whether or not you write static, so both rows show Target=null.
Option 1: a function pointer, the only compile-time guarantee built into C#
C# 9 added function pointers, and a managed function pointer can only point at a static method. That is exactly the constraint being asked for, enforced by the compiler with no extra tooling:
// .NET 11 (SDK 11.0.100), C# 15. File-based app: dotnet run fnptr.cs
#:property AllowUnsafeBlocks=true
unsafe
{
var demo = new Demo();
int fortyTwo = 42;
Console.WriteLine(Runner.Run(5, &Demo.Square)); // OK, prints 25
Console.WriteLine(Runner.Run(5, &demo.Instance)); // CS8759
Console.WriteLine(Runner.Run(5, static x => x * 2)); // CS1660
Console.WriteLine(Runner.Run(5, &Local)); // CS8759
int Local(int x) => x + fortyTwo;
}
class Demo
{
public static int Square(int x) => x * x;
public int Instance(int x) => x;
}
static unsafe class Runner
{
public static int Run(int input, delegate*<int, int> work) => work(input);
}
The compiler errors, verbatim from SDK 11.0.100:
error CS8759: Cannot create a function pointer for 'Demo.Instance(int)' because it is not a static method
error CS1660: Cannot convert lambda expression to type 'delegate*<int, int>' because it is not a delegate type
error CS8759: Cannot create a function pointer for 'Local(int)' because it is not a static method
The price is steep for most APIs, which is why this is rarely the right answer for a general-purpose helper:
- Callers need
unsafeandAllowUnsafeBlocks. - Lambdas are not accepted at all, not even
staticones. Callers must write a named static method. - A pointer type cannot be a generic type argument, so it cannot flow through
Func<...>,Task.Run<T>or aList<T>. If your helper hands the work to the thread pool, you end up wrapping the call in a delegate inside your own code, which is fine because you control that delegate.
It is the right tool for low-level, synchronous, hot-path callbacks (interop, dispatch tables, parsers). For an ordinary public API that should take a lambda, use one of the next two options.
Option 2: a runtime check on Delegate.Target
If a runtime assertion is acceptable, the table above gives you the rule: a single delegate captures no state when its Target is null, or when the target is a compiler-generated class with no instance fields (the <>c lambda cache). Everything else is a closure (<>c__DisplayClass), a this reference, a bound first argument, or some runtime object.
// .NET 11 (SDK 11.0.100), C# 15
using System.Reflection;
using System.Runtime.CompilerServices;
static class Guard
{
public static bool CapturesNoState(Delegate d)
{
foreach (Delegate single in d.GetInvocationList())
{
object? target = single.Target;
if (target is null)
continue; // static method, or an open instance delegate
Type type = target.GetType();
bool isLambdaCache =
type.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false)
&& type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Length == 0;
if (!isLambdaCache)
return false; // closure, 'this', or a bound first argument
}
return true;
}
public static void RequireNoState(Delegate d, [CallerArgumentExpression(nameof(d))] string? expression = null)
{
if (!CapturesNoState(d))
throw new ArgumentException($"'{expression}' must not capture state. Use a static lambda or a static method.", nameof(d));
}
}
Use it at the top of the method that receives the delegate:
public static void RunTask<P, R>(P parameter, Func<P, R> work, Action<R> onResult)
{
Guard.RequireNoState(work);
// ...
}
The [CallerArgumentExpression] parameter puts the caller’s source text in the exception message, the same trick described in what [CallerArgumentExpression] captures and how to use it in guard methods.
Know what this check is built on before relying on it:
- It reads compiler implementation details. The
<>csingleton pattern is how Roslyn has emitted non-capturing lambdas for many releases, and it is what SDK 11.0.100 produces, but no spec promises it. If a future compiler emitted such lambdas as true static methods,Targetwould becomenulland the check would still pass. If it started caching them on some type with instance fields, the check would start failing loudly, which is the safe direction. - It cannot tell
staticlambdas from lambdas that merely happen not to capture. Both rows above produce the same<>ctarget. The runtime check enforces “captures nothing”, which is usually what you actually want; it cannot enforce “the caller wrote thestatickeyword”. - “No captured state” is not “no side effects”. A static method or static lambda can still mutate static fields, write to the console, or call into a singleton. The question’s goal of proving the work is side-effect free is out of reach for any of these techniques.
- It rejects some harmless delegates. A compiled expression tree with only constants is rejected because its target is a
Closure. So is a method group on an immutable object, such as"abc".Contains. If you need to accept those, add explicit allow-list rules. - The reflection call is not trim-safe.
GetType().GetFields(...)produces IL2075 warnings (the probe above shows them when built with the default file-based app settings). The check was only run on CoreCLR with JIT. Under Native AOT, if reflection metadata for a closure’s fields is stripped,GetFieldscould return an empty array and a capturing lambda would look stateless, so test it in your AOT build before trusting it there.
Option 3: a Roslyn analyzer behind [RequireStatic]
The only way to get a compile-time error for “you passed a non-static lambda” while still accepting lambdas is to write the rule yourself. An analyzer is small: look at every argument whose parameter carries a RequireStaticAttribute, unwrap the conversion to the delegate type, and inspect what is being converted.
// Roslyn analyzer project: netstandard2.0, Microsoft.CodeAnalysis.CSharp 4.14.0
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class RequireStaticAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor Rule = new(
id: "RS9001",
title: "Argument must be a static lambda or a static method",
messageFormat: "Parameter '{0}' requires a static lambda or a static method group, but got {1}",
category: "Usage",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterOperationAction(AnalyzeArgument, OperationKind.Argument);
}
private static bool HasRequireStatic(ISymbol symbol) =>
symbol.GetAttributes().Any(a => a.AttributeClass?.Name == "RequireStaticAttribute");
private static void AnalyzeArgument(OperationAnalysisContext context)
{
var argument = (IArgumentOperation)context.Operation;
if (argument.Parameter is not { } parameter || !HasRequireStatic(parameter))
return;
IOperation value = argument.Value;
while (value is IConversionOperation conversion)
value = conversion.Operand;
string? problem = value switch
{
IDelegateCreationOperation { Target: IAnonymousFunctionOperation lambda }
=> IsStaticLambda(lambda) ? null : "a lambda without the 'static' modifier",
IDelegateCreationOperation { Target: IMethodReferenceOperation reference }
=> reference.Method.IsStatic && reference.Instance is null
? null
: $"a method group bound to an instance ('{reference.Method.Name}')",
IAnonymousFunctionOperation lambda
=> IsStaticLambda(lambda) ? null : "a lambda without the 'static' modifier",
IParameterReferenceOperation p when HasRequireStatic(p.Parameter)
=> null, // already checked at our caller
IDefaultValueOperation or ILiteralOperation { ConstantValue: { HasValue: true, Value: null } }
=> null,
_ => "a delegate value whose origin cannot be checked"
};
if (problem is not null)
context.ReportDiagnostic(Diagnostic.Create(Rule, argument.Value.Syntax.GetLocation(), parameter.Name, problem));
}
private static bool IsStaticLambda(IAnonymousFunctionOperation lambda) =>
lambda.Syntax is AnonymousFunctionExpressionSyntax syntax
&& syntax.Modifiers.Any(SyntaxKind.StaticKeyword);
}
The analyzer project file targets netstandard2.0 (analyzers are loaded into the compiler, which may run on .NET Framework inside Visual Studio) and references the Roslyn packages privately:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<IsRoslynComponent>true</IsRoslynComponent>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" PrivateAssets="all" />
</ItemGroup>
</Project>
Reference 4.14.0 rather than the newest 5.x package on purpose: an analyzer must not reference a newer Roslyn than the compiler that loads it. 4.14 is the compiler in Visual Studio 2022 17.14 and the 9.0.300 SDK, so the analyzer loads there and in anything newer, including SDK 11.0.100. Drop to an older package if you must support older compilers; every API used here has existed since Roslyn 3.x. The consuming project references the analyzer as an analyzer, not as a library:
<ProjectReference Include="../RequireStatic.Analyzers/RequireStatic.Analyzers.csproj"
OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
The API side only needs the attribute. The analyzer matches it by name, so it can live in any namespace of the library that exposes the API:
// .NET 11 (SDK 11.0.100), C# 15
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RequireStaticAttribute : Attribute;
public static class TaskRunner
{
public static int Run(int input, [RequireStatic] Func<int, int> work) => work(input);
// Forwarding a [RequireStatic] parameter to another [RequireStatic] parameter is allowed.
public static int RunTwice(int input, [RequireStatic] Func<int, int> work) => Run(Run(input, work), work);
}
And the call sites, as compiled against SDK 11.0.100:
// .NET 11 (SDK 11.0.100), C# 15. Program.cs; the BAD block is built with -p:DefineConstants=BAD
var worker = new Worker();
int offset = 10;
Console.WriteLine(TaskRunner.Run(5, static x => x * 2)); // OK
Console.WriteLine(TaskRunner.Run(5, Worker.Square)); // OK
Console.WriteLine(TaskRunner.Run(5, StaticLocal)); // OK
#if BAD
Console.WriteLine(TaskRunner.Run(5, x => x * 2)); // RS9001: no 'static'
Console.WriteLine(TaskRunner.Run(5, x => x + offset)); // RS9001: captures (and no 'static')
Console.WriteLine(TaskRunner.Run(5, worker.AddState)); // RS9001: instance method group
Func<int, int> stored = static x => x;
Console.WriteLine(TaskRunner.Run(5, stored)); // RS9001: opaque variable
#endif
static int StaticLocal(int x) => x - 1;
class Worker
{
private int _state = 3;
public static int Square(int x) => x * x;
public int AddState(int x) => x + _state;
}
Program.cs(9,37): error RS9001: Parameter 'work' requires a static lambda or a static method group, but got a lambda without the 'static' modifier
Program.cs(10,37): error RS9001: Parameter 'work' requires a static lambda or a static method group, but got a lambda without the 'static' modifier
Program.cs(11,37): error RS9001: Parameter 'work' requires a static lambda or a static method group, but got a method group bound to an instance ('AddState')
Program.cs(13,37): error RS9001: Parameter 'work' requires a static lambda or a static method group, but got a delegate value whose origin cannot be checked
The valid calls compile and print 10, 25 and 4, and RunTwice forwarding its own [RequireStatic] parameter produces no diagnostic.
A few design decisions are worth calling out, since you may want to change them:
- Stored delegates are rejected.
storedholds a static lambda, but the analyzer works on one call site at a time and cannot see where a local’s value came from. Rejecting is the strict choice. A softer version reports a warning for that case, or tracks simple local assignments with a data-flow pass. - It checks the
statickeyword, not capture.x => x * 2captures nothing and would pass the runtime check, but the analyzer flags it. That is the point of a compile-time rule: it forces the caller to state intent, and the compiler then guarantees that later edits to the lambda body cannot introduce a capture. - Non-
staticlocal functions are rejected even when they capture nothing, for the same reason:IMethodSymbol.IsStaticreflects thestaticmodifier, not what the emitter does. - The severity is
Errorby default. Consumers can downgrade it per project in.editorconfigwithdotnet_diagnostic.RS9001.severity = warning. Pick your own ID prefix before shipping;RSis used by Roslyn’s own analyzers, and the Microsoft.CodeAnalysis.Analyzers package will also nag about release tracking (RS2008) until you addAnalyzerReleases.Shipped.mdfiles.
To ship this with a library, pack the analyzer DLL under analyzers/dotnet/cs in the same NuGet package as the API. The Microsoft Learn tutorial on writing an analyzer and code fix covers packaging and adds a code fix, which here could insert the static keyword automatically. If you have not built Roslyn components before, what a source generator is and when you need one walks through the same project setup from the generator side.
Picking one
- You control both sides and the callback is synchronous and hot: take a
delegate*<...>. It costs nothing, needs no tooling, and is a hard guarantee. The same idea shows up in building a static dispatch table of instance methods, where static lambdas with an explicitselfparameter replace instance-bound delegates. - You ship a public API that takes lambdas: ship the analyzer with the library, and keep the runtime check as a debug assertion for callers that suppress the diagnostic or call through reflection.
- You only need to catch mistakes in tests: the runtime check alone is a few lines, but read its limits above.
Whichever you choose, also consider whether the caller-side static modifier is enough on its own. It is free, it prevents accidental captures at the point where they happen, and it lets the runtime reuse one cached delegate instead of allocating a closure on every call, which is the allocation difference shown in Task.Run vs Task.Factory.StartNew vs ThreadPool.QueueUserWorkItem. A related surprise about what a delegate’s Target really points to, a boxed copy of a struct, is behind why list.ForEach(hashCode.Add) leaves a HashCode unchanged.
Sources
- Static anonymous functions proposal, C# 9 (the “no guarantee of a static method in metadata” rule)
- Lambda expressions, Microsoft Learn
- Unsafe code and function pointers, Microsoft Learn
Delegate.TargetandDelegate.GetInvocationList- Tutorial: Write your first analyzer and code fix, Microsoft Learn
- How can I require a delegate/lambda to be static? on Stack Overflow
Comments
Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.