Require a delegate parameter to avoid closure #9079
Replies: 1 comment 5 replies
-
If the caller does not want the lambda to capture state they can apply a using System;
int a = 4;
Console.WriteLine(Increment(static ()=>a)); // error CS8820: A static anonymous function cannot contain a reference to 'a'.
int Increment(Func<int> valueProvider) => valueProvider()+1; |
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Background and Motivation
Enforce a delegate parameter not to capture closure.
Proposed API
The following code prints 5 to the console.
The proposal adds a C# language constraint on
valueProvider
parameter, so that the following code returns a compile time error:But the following would compile:
This would allow (for the author of Increment API) to avoid accidental boxing or enforce that the delegate can only work with validated parameters:
Usage Examples
Using
myset2
would cause a compile time error in(a,b) => myset2.Count + a)
Beta Was this translation helpful? Give feedback.
All reactions