static lambda functions are not static methods
Stating with C# 9.0, you can use the static
modifier on lambda functions. For instance, you can write the following code:
enumerable.Select(static x => x * 2);
When you use the static
modifier on a lambda function, the compilers ensures that there is no capture of variables from the enclosing scope. This allows the compiler to generate better code. Indeed, it can cache the lambda function and reuse it across multiple calls. This can improve performance in some scenarios. However, the code generated by the compiler is the same whether you use the static
modifier or not. So, it is very similar to an analyzer except this is built into the language.
If you look at the generated code, you'll see that the lambda function is not a static method. It is an instance method.
[Serializable]
[CompilerGenerated]
private sealed class <>c
{
public static readonly <>c <>9 = new <>c();
public static Func<int, int> <>9__0_0;
// This method is not static
internal int <<Main>$>b__0_0(int i)
{
return i + 1;
}
}
Why does the compiler generate an instance method instead of a static method? The reason lies in how delegates work. Delegates use the instance calling convention, meaning they expect to call instance methods. When a lambda function is converted to a delegate, the compiler generates an instance method to match this convention. If the lambda were a static method, the compiler would need to use a shuffle thunk to rearrange the arguments, which could negatively impact performance.
Do you have a question or a suggestion about this post? Contact me!