dotnet / dotnet/csharplang

Fixed/moveable variables versus locals captured in a lambda

Open
#2,496 0 comments 0 reactions 1 assignee Claimed by @MadsTorgersen View on GitHub
Spec
Dominant language
C#
Stars
12.7k
Forks
1.1k
Avg merge
11h 1m
Merged PRs (30d)
3

Description

The language spec (18.3 Fixed and moveable variables) says

> In precise terms, a fixed variable is one of the following:
> - A variable resulting from a _simple-name_ (§7.6.2) that refers to a local variable or a value parameter, unless the variable is captured by an anonymous function.
> - A variable resulting from a _member-access_ (§7.6.4) of the form `V.I`, where `V` is a fixed variable of a struct-type.
> - A variable resulting from a _pointer-indirection-expression_ (§18.5.1) of the form `*P`, a _pointer-member-access_ (§18.5.2) of the form `P->I`, or a _pointer-element-access_ (§18.5.3) of the form `P[E]`.
> All other variables are classified as moveable variables.

But testing this on the following program

``` cs
using System;

unsafe struct S
{
public fixed int buffer[1];
public int i;
}

unsafe class Test
{
private void example1()
{
S data = new S();
Func lambda = () => data;
fixed (int* p = &data.i) // ok; data is captured
{
}
fixed (int* p = data.buffer) // ok; data is captured
{
}
}
}
```

We find that Roslyn reject both attempts, complaining that you can't take the address of a variable that has been captured by a lambda, AND that you can't use the fixed statement to take the address of an already fixed expression.

Why does the language forbid using a fixed statement for a fixed variable? It would just be a no-op. Allowing it would sidestep having to specify which variables are captured in an async method. We could just say that there are no fixed variables in an async method, and force people to use the fixed statement (which might sometimes be a no-op).

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.