Skip to content

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

@mattwar

Description

@mattwar

Allow Func<int, string> = static i => i.ToString();.

  • Proposal added (here)
  • 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.

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.

int y = 10;
someMethod(static x => x + y); // error!
const int y = 10;
someMethod(static x => x + y); // okay :-)

LDM history:

  • 10/21/2019

Metadata

Metadata

Assignees

Labels

Implemented Needs ECMA SpecThis feature has been implemented in C#, but still needs to be merged into the ECMA specificationProposal champion

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions