Static anonymous functions #110886
Answered
by
CyrusNajmabadi
sharpzilla
asked this question in
General
Replies: 1 comment 4 replies
-
The total point is to disallow capture for the given lambda. It's more a hint about other readers that "this is performance sensitive, capturing is not allowed". If you are not writing such performance sensitive code, you can simply ignore this feature. |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Can someone explain to me why I might need to write static in anonymous functions?
I've read several sources, such as:
Static anonymous functions in C# 9
Discussion on GitHub
And I got even more confused.
From what I understand, adding static in anonymous functions does not guarantee that the compiler-generated class will have a static method.
If I write code like this and don’t add the static keyword, the generated code will be identical to what it would have been if I had written static.
User code:
Compiler generated
What the static keyword definitely allows is highlighting at compile time when a local variable from the method context is captured in the anonymous function.
But now, instead of a concise lambda expression, I also have to write static before it, and the code starts to get bloated. What’s the point of using the static keyword if the output is identical?
The only advantage I can see from using static is the compiler hint. But along with that, I have to write more code compared to the approach where I don’t use the static keyword. I can’t fully trust the compiler and IDE to ensure there is no context capture. Let me explain why I think so. There are CodeFixers that will add static throughout the project for me, but when I look at a lambda expression that’s longer than y => y * y, I can’t be sure whether the person who wrote it deliberately didn’t use static because there’s a variable capture in the body of the expression, or if they simply forgot to add it. So I still end up scanning with my eyes to check if there’s context capture.
Of course, I can spend time writing static and quickly see the results from the code analyzer. But it seems like this doesn’t simplify my life at all.
If static isn’t used consistently throughout the project, it seems to lose its purpose, and I still have to manually analyze each lambda expression. There’s no unified convention in the project. For instance, if I’m using Entity Framework Core Fluent API to configure tables, the code becomes cluttered with static this or static that. I have to visually search for the actual essence of the code.
Am I missing some details that make using static in lambda expressions useful?
Beta Was this translation helpful? Give feedback.
All reactions