Introduction

.NET 5 から導入され、 .NET 6 からデフォルトとして有効になった **最上位ステートメント (top-level statements)**。

1
2
3
4
5
6
7
8
9
10
11
12
using System;

namespace MyApp // Note: actual namespace depends on the project name.
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

1
Console.WriteLine("Hello, World!");

と等価と言われても困ります。

たしかに、Program クラスを作って、Main 関数を書いて、というのはボイラープレートと同義だが、だからと言ってこれはやり過ぎだと思う。
私と同じ意見なのか

上記の issue で意見を募っており、2022年7月9日現在、

Preference

Up-vote this comment if you support the use of top-level statements in project templates.
プロジェクト・テンプレートでトップレベルステートメントを使用することを支持する場合は、このコメントをアップ投票してください。

83対702

Up-vote this comment if you prefer project templates to use the code created in previous .NET versions.
以前の.NETバージョンで作成されたコードを使用するプロジェクト・テンプレートを希望する場合、このコメントをアップグレードしてください。

920対24

Up-vote this comment if you would like to be given a choice between top-level statements code and the code created in previous .NET versions.
トップレベルステートメントのコードと以前の.NETバージョンで作成されたコードのどちらかを選択できるようにしたい場合、このコメントをアップ投票してください。

894対44

と、圧倒的な大差で反対意見が優勢。

その結果、Visual Studio 2022 17.3.0 (Preview 1.1) から、.NET 6 のプロジェクト作成時、Do not use top-level statements というオプションが付与された。

が、コマンドプロンプトからプロジェクトを作成する場合はどうしようもない。
それの対処を記載する。

How to resolve?

上記にあるように、.NET 5 でプロジェクトを作成し、手動で .NET 6 に更新するという手段しかない模様。

1
$ dotnet new console --framework net5.0

作成された .csproj を開き、TargetFramework を変更。

1
2
3
4
5
6
7
8
9
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
- <TargetFramework>net5.0</TargetFramework>
+ <TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

</Project>

必要に応じて Implicit using directives (暗黙的な using ディレクティブ)Nullable (Null許容) を有効にすれば完成。

1
2
3
4
5
6
7
8
9
10
<Project Sdk="Microsoft.NET.Sdk">

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

</Project>