Roslyn: static local function compilation error while referencing constants

Created on 31 May 2019  路  3Comments  路  Source: dotnet/roslyn

Version Used:
VS 16.1.1 stock compiler (ie no NuGet compiler packages)

Steps to Reproduce:

```c#
const int prevpage = -1, nextpage = -2;
static int StringActionToInt32(string act) => act == "+" ? nextpage : act == "-" ? prevpage : int.Parse(act);


**Behavior**:
That piece of code gives the following compilation error:

2>MainWindow.xaml.cs(184,80,184,88): error CS8421: A static local function cannot contain a reference to 'nextpage'.
2>MainWindow.xaml.cs(184,104,184,112): error CS8421: A static local function cannot contain a reference to 'prevpage'.
```

Note that this was only observed after following the automatic static function refactoring, which correctly added the static modifier on the function and nothing else, so the refactoring engine is also expecting this to work.

Area-Compilers Bug

Most helpful comment

The LDM today approved fixing this:

Static local functions

A static local function is currently forbidden from capturing a local. Even a constant.

I propose that a static local function be permitted to capture a local constant.

Resolution: approved.

All 3 comments

@cston is it permitted to reference a constant from an enclosing scope in a static local function?

Note: the "make local function static" analyzer does this check:

c# var analysis = semanticModel.AnalyzeDataFlow(localFunction); var captures = analysis.CapturedInside; if (analysis.Succeeded && captures.Length == 0)

So, from the API perspective, we're not capturing anything. This def seems odd to me.

The LDM today approved fixing this:

Static local functions

A static local function is currently forbidden from capturing a local. Even a constant.

I propose that a static local function be permitted to capture a local constant.

Resolution: approved.

Was this page helpful?
0 / 5 - 0 ratings