Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

417
Visualizações
In C#, why can't I populate a local variable using its address, then use the variable later?

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://docs.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).

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The C# specification says the following (my bold):

23.4 Fixed and moveable variables

The address-of operator (§23.6.5) and the fixed statement (§23.7) divide variables into two categories:
Fixed variables and moveable variables.

...snip...

The & operator (§23.6.5) permits the address of a fixed variable to be obtained without restrictions. However, because a moveable variable is subject to relocation or disposal by the garbage collector, the address of a moveable variable can only be obtained using a fixed statement (§23.7), and that address remains valid only for the duration of that fixed statement.

In precise terms, a fixed variable is one of the following:

  • A variable resulting from a simple-name (§12.7.3) that refers to a local variable, value parameter, or parameter array, unless the variable is captured by an anonymous function (§12.16.6.2).
  • .....

So it's explicitly forbidden by the spec. As to why it's forbidden, for that you would have to ask the language designers, but considering how much complexity is involved in capturing variables, it is somewhat logical.

over 4 years ago · Santiago Trujillo Relatório

0

I guess the reason is simple: Too complex to compile.

There are 2 problems the compiler has to solve:

  1. Generate a clourse for the anonymous method.
  2. Synchronize the value of the variable.

Let's assume the following codes are valid.

unsafe void Function()
{
    int length = 1;
    void bar() => Console.WriteLine(length);
    bar();
    foo(&length);
    bar();
}

unsafe void foo(int* i) { (*i)++; }

Expected result is:

1
2

To solve the first problem C# will generate an anonymous class to hold the upvalue.

Here is the pseudocode:

class _Anonymous
{
    public int _length;

    public void _bar() { Console.WriteLine(_length); }
}

unsafe void Function()
{
    int length = 1;
    var a = new _Anonymous { _length = length };
    a._bar();
    foo(&length);
    a._bar();
}

To solve the second problem C# uses the generated field instead of the original local variable.

unsafe void Function()
{
    //int length = 1;
    var a = new _Anonymous { _length = 1 };
    a._bar();
    foo(&a._length);
    a._bar();
}

These are all the works that a compiler can do. But till now the codes still won't work, we need an extra fixed block.

unsafe void Function()
{
    var a = new _Anonymous { _length = 1 };
    a._bar();
    fixed (int* p = &a._length)
        foo(p);
    a._bar();
}

So the limitation can be removed with a smarter compiler, but things get more easy if we forbid such kind of codes.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda