-
The reference implementation roslyn currently rejects the following code with the error message:
Code: using System;
class X
{
public static void Main(string?[]? args)
{
int x = 1;
var lambda = ref int () =>
{
return ref x;
};
ref int r = ref lambda();
r++;
r++;
Console.WriteLine(x);
}
} If I write the lambda "manually" I get something like: using System;
class Capture
{
public int x;
public ref int Invoke()
{
return ref x;
}
}
public delegate ref T RefDelegate<T>();
class X
{
public static void Main()
{
var c = new Capture();
c.x = 1;
RefDelegate<int> lambda = c.Invoke;
ref int r = ref lambda();
r++;
r++;
Console.WriteLine(c.x);
Console.WriteLine(r);
}
} which compiles and runs perfectly fine. Is there any reason why the code is rejected? Is this specified in the spec or a compiler limitation? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
If I write the lambda like: var lambda = ref int () =>
{
ref int scopedXref =ref System.Runtime.CompilerServices.Unsafe.AsRef(x);
return ref scopedXref;
}; I can make the captured local |
Beta Was this translation helpful? Give feedback.
If I write the lambda like:
I can make the captured local
scoped
. But because it is actually a field which lives on the heap, shouldn't it be implicitlyscoped
?