0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#のトップレベルステートメントでは、暗黙的にstring[] args定義されていて、コマンドライン引数を参照できる

Posted at

.NET 10で、単一ファイルをdotnet runで実行できるようになる予定です(2025年5月末時点)

これにより、トップレベルステートメントで作ったC#のコードに、コマンドライン引数を渡して実行したい場面が増えるでしょう。

C#のトップレベルステートメントでは、暗黙的にstring[]型のargsが定義されています。コマンドライン引数が入力された場合、args変数で入力されたコマンドライン引数を参照できます。

次のようなC#コード「hello.cs」を、

if(args.Length == 0) {
    Console.WriteLine("args is empty.");
}

foreach(var arg in args) {
    Console.WriteLine(arg);
}

次のようにdotnet runで実行します。(.NET 10 preview 4以降が必要)

dotnet run hello.cs -- Hello world! "I love C#."

すると、次のように表示されます。

Hello
world!
I love C#.

なお、args変数がnullになることはありません。コマンドライン引数が指定されなかった場合、空配列となります。

先のhello.csを、次のようなコマンドで実行すると、

dotnet run hello.cs

次のように表示されます。

args is empty.

dotnet run file.csで、単一ファイルを実行できるのとても楽しみですね。

リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?