ref struct closures for lambdas
Spec: https://github.com/dotnet/csharplang/blob/main/proposals/ref-struct-closures.md
Discussion: #10210
Summary
The proposal is to allow C# to convert lambda expressions to generic type parameters constrained to specific IFunc/IAction interfaces. Furthermore, the type parameter should be marked allows ref struct and the backing closure should be a ref struct.
For instance, the following code
List<int> list = [1, 2, 3];
Console.Write(FirstOrNull(list, x => x % 2 == 0));
static int? FirstOrNull<TPred>(List<int> list, TPred pred)
where TPred : allows ref struct, IFunc<int, bool>
{
var filtered = new List<int>();
foreach (var item in list)
{
if (pred.Invoke(item))
{
return item;
}
}
return null;
}
would compile and produce the output "2". The generated code for the lambda would look equivalent to
ref struct __Closure : IFunc<int, bool>
{
public bool Invoke(int x) => x % 2 == 0;
}
ref struct closures for lambdas
Spec: https://github.com/dotnet/csharplang/blob/main/proposals/ref-struct-closures.md
Discussion: #10210
Summary
The proposal is to allow C# to convert lambda expressions to generic type parameters constrained to specific
IFunc/IActioninterfaces. Furthermore, the type parameter should be markedallows ref structand the backing closure should be a ref struct.For instance, the following code
would compile and produce the output "2". The generated code for the lambda would look equivalent to