dotnet / dotnet/csharplang

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

Open
#275 71 comments 121 reactions 1 assignee Claimed by @jcouv View on GitHub
Implemented Needs ECMA Spec Proposal champion
Dominant language
C#
Stars
12.7k
Forks
1.1k
Avg merge
11h 1m
Merged PRs (30d)
3

Description

Allow `Func = 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

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.