New array initalizer syntax in C# 12 doesn't compile in VS 2022 17.8

842 views Asked by At

Currently using Visual Studio 2022 17.8 to play with .NET 8 and C# 12 changes.

I'm getting IDE0300 inspection hints on field declarations like this, telling me to convert to a collection expression instead, for example:

private readonly int[] _values = { 1, 2, 3, 4 };

converts to

private readonly int[] _values = [1, 2, 3, 4];

But I get red squigglies immediately after applying the inspection.

I thought this feature was supported in C# 12 but it appears to be broken. I've checked that I'm using the latest language version in the project settings, so it's not that.

Local declarations fail as well:

int[] values = [1, 2, 3, 4];

Parsing errors such as "Identifier expected", "Initializer expected", "; expected" are shown in editor window depending on where I hover.

Is this happening for anyone else? Is it a known issue? I can't find any open issue currently.

EDIT: It's a bug in the version of ReSharper I'm using (2023.2.3), not a compiler error. Have raised with JetBrains and updated wording to be clearer.

2

There are 2 answers

1
Axel Kemper On

The following compiles without problems for me:

internal class Program
{
    private static readonly int[] _values = { 1, 2, 3, 4 };

    static void Main(string[] args)
    {
        int[] values = [1, 2, 3, 4];

        Console.WriteLine($"{values.Length} value {string.Join(' ', values.Select(x => x.ToString()))}");
    }
}

My project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
0
Oleg Fridman On

The problem is indeed with Jetbrains Resharper 2023.2.3 or older, tracked here: https://youtrack.jetbrains.com/issue/RSRP-494070/Support-for-C-12-collection-expressions

They've since resolved it and the fix is available in the EAP version (2023.3.0.8 released Nov 20): https://www.jetbrains.com/resharper/nextversion/