rksoftware

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

C# 2.0 以降の新機能の確認 - C# 8.0 - 静的ローカル関数

C# 2.0 以降の新機能を一つづつ確認していきます。
以前に一度行ったのですが、公式ドキュメント再編でリンク切れしているところを見つけてしまったので。今ならもっと簡潔なサンプルが欠けるところもあるだろうし、せっかくなので今もう一度確認して行きます。

静的ローカル関数

 https://docs.microsoft.com/ja-jp/dotnet/csharp/programming-guide/classes-and-structs/local-functions#local-function-syntax
 ローカル関数を static にできる。

{// これはコンパイルエラー 
    int x = 0;
    // localFunction(x);
    Console.WriteLine(x);

    // static なので外部の変数をキャプチャできずエラー
    // static int localFunction(int y) => ++x;
}
{// むしろキャプチャできないことがうれしい
    int x = 0;
    x = localFunction(x);
    Console.WriteLine(x);

    static int localFunction(int y) => ++y;
}