Anonymous functions and lambdas are able to use any variables in scope which can be very convenient. It can also result in unexpected behavior and more memory usage (all variables referenced by an anonymous function or lambda are moved into a special class called a closure named DisplayClass_x
) so that they can outlive the original method scope on the heap.
C# 9.0 allows you to specify that an anonymous function or lambda is static
to indicate no references to variables is intended. This is especially useful for marking critical hot-paths where the additional creation of a closure on each call could use a large amount of memory and undesired performance regressions.
Code
C#
const int y = 10;
someMethod(static x => x + y);
C#
int y = 10;
someMethod(x => x + y);