Consider the following code:
private unsafe void Function()
{
int length;
// This line raises error CS1686, "Local 'length' or its members cannot have their address taken and be used inside an anonymous method or lambda expression".
glGetProgramiv(1, GL_PROGRAM_BINARY_LENGTH, &length);
FunctionWithLambda(() => Console.WriteLine(length));
}
private void FunctionWithLambda(Action callback)
{
callback();
}
Note that I'm taking the address of length
(a local variable), then using the variable itself (not its address) in a lambda. I understand why a local variable address can't be used in a lambda directly (see Why cannot I pass the address of a variable to an anonymous function?, among other examples), but why can't I use the value of length
once assigned (even if that assignment happens to use the &
operator)? The official documentation for error CS1686 (https://learn.microsoft.com/bs-latn-ba/dotnet/csharp/misc/cs1686) hasn't clarified this confusion.
My assumption is that this is simply a language limitation, but I'm curious if there's an underlying technical reason I'm missing. Also note I'm not asking how to work around this problem (I know I can easily copy length
to another local variable first).