IssueRaiser

Proposal: Use static keyword for lambdas to disallow capturing locals and parameters (VS 16.8, .NET 5)

Allow `Func<int, string> = static i => i.ToString();`. - [x] Proposal added ([here](https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/static-lambdas.md)) - [x] Discussed in LDM 2019-10-21 - [ ] Decision in LDM - [ ] Finalized (done, rejected, inactive) - [ ] Spec'ed ---- To avoid accidentally capturing any local state when supplying lambda functions for method arguments, prefix the lambda declaration with the static keyword. This makes the lambda function just like a static method, no capturing locals and no access to this or base. ```cs int y = 10; someMethod(x => x + y); // captures 'y', causing unintended allocation. ``` with this proposal you could the static keyword to make this an error. ```cs int y = 10; someMethod(static x => x + y); // error! ``` ```cs const int y = 10; someMethod(static x => x + y); // okay :-) ``` LDM history: - 10/21/2019

Posted by mattwar on Mar 15, 2017, 8:34 PM

Tags

Related issues

Raise real-world problems, find people facing the same issue, and discuss solutions.4,500 issues0 comments

github (Software)

Proposal: Use static keyword for lambdas to disallow capturing locals and parameters (VS 16.8, .NET 5)

mattwarMar 15, 2017, 8:34 PM

Allow `Func<int, string> = static i => i.ToString();`. - [x] Proposal added ([here](https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/static-lambdas.md)) - [x] Discussed in LDM 2019-10-21 - [ ] Decision in LDM - [ ] Finalized (done, rejected, inactive) - [ ] Spec'ed ---- To avoid accidentally capturing any local state when supplying lambda functions for method arguments, prefix the lambda declaration with the static keyword. This makes the lambda function just like a static method, no capturing locals and no access to this or base. ```cs int y = 10; someMethod(x => x + y); // captures 'y', causing unintended allocation. ``` with this proposal you could the static keyword to make this an error. ```cs int y = 10; someMethod(static x => x + y); // error! ``` ```cs const int y = 10; someMethod(static x => x + y); // okay :-) ``` LDM history: - 10/21/2019

Comments (0)

No comments yet. Start the discussion.

Comment on this issue