rksoftware

Visual Studio とか C# とかが好きです

C# 12 を試す - Visual Studio Code

そろそろ C# 12 の時期なので予習を始めなければなりません。

というわけで公式サイトを見てみると .NET 8 SDK のプレビュー版か Visual Studio の Preview 版で試せるとのこと。
learn.microsoft.com

■ Visual Studio Code

試しに以前に Visual Studio で試した C# 12 の新機能を一通り書いたコードを Visual Studio Code で開いてみました。

using System.Runtime.CompilerServices;

using MyType = (int x, int y);

// See https://aka.ms/new-console-template for more information
Console.WriteLine(new Test("Hello, World! 1").Name());

Console.WriteLine(new MyType(1, 2));

int[] row0 = [1, 2, 3];
int[] row1 = [4, 5, 6];
int[] row2 = [7, 8, 9];
int[] single = [.. row0, .. row1, .. row2];
foreach (var element in single)
{
    Console.Write($"{element}, ");
}

var lamda = (int a = 1) => a + a;
Console.WriteLine(lamda());

var buffer = new Buffer();
for (int i = 0; i < 10; i++)
{
    buffer[i] = i;
}

foreach (var i in buffer)
{
    Console.WriteLine(i);
}

var c = new C();
c.InterceptableMethod(1); // (L1,C1): prints "interceptor 1"
c.InterceptableMethod(1); // (L2,C2): prints "other interceptor 1"
c.InterceptableMethod(2); // (L3,C3): prints "other interceptor 2"
c.InterceptableMethod(1); // prints "interceptable 1"



class Test(string name)
{
    public string Name() { return name; }
}

[System.Runtime.CompilerServices.InlineArray(10)]
public struct Buffer
{
    private int _element0;
}

class C
{
    public void InterceptableMethod(int param)
    {
        Console.WriteLine($"interceptable {param}");
    }
}

// generated code
static class D
{
    [InterceptsLocation(@"C:\Sample\cs12\ConsoleAppVSPreview\ConsoleAppVSPreview\Program.cs", line: 36, character: 3)] // refers to the call at (L1, C1)
    public static void InterceptorMethod(this C c, int param)
    {
        Console.WriteLine($"interceptor {param}");
    }

    [InterceptsLocation(@"C:\Sample\cs12\ConsoleAppVSPreview\ConsoleAppVSPreview\Program.cs", line: 37, character: 3)] // refers to the call at (L2, C2)
    //[InterceptsLocation(@"C:\Sample\cs12\ConsoleAppVSPreview\ConsoleAppVSPreview\Program.cs", line: 38, character: 3)] // refers to the call at (L3, C3)
    public static void OtherInterceptorMethod(this C c, int param)
    {
        Console.WriteLine($"other interceptor {param}");
    }
}

namespace System.Runtime.CompilerServices
{
    sealed class InterceptsLocationAttribute(string filePath, int line, int character) : Attribute
    {
    }
}
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <LangVersion>Preview</LangVersion>
    <Features>InterceptorsPreview</Features>
  </PropertyGroup>

</Project>

エラーなく開けました。

実行も OK。素晴らしい。