Thursday, October 24, 2024

Command-line argument with Top level statements in C#

We will see how can we use command-line argument with top-level statements in C#.

C# 9.0 introduced top-level statements, allowing you to write C# applications without explicitly defining a Main method. To use command-line arguments with top-level statements, you can access the args parameter directly within the top-level statements.

Here's a step-by-step guide:

1. Create a new C# file: Create a new C# file with a .cs extension, for example, Program.cs.

2. Write the code with top-level statements: Write the C# code using top-level statements. Access the args parameter to retrieve command-line arguments.
using System;

if (args.Length > 0)
{
 Console.WriteLine("Command-line arguments:");
 foreach (var arg in args)
 {
  Console.WriteLine(arg);
 }
}
else
{
 Console.WriteLine("No command-line arguments provided.");
}

In this example, we check if any command-line arguments were passed. If so, we print them to the console. If not, we print a message indicating that no arguments were provided.

3. Compile and Run: To compile and run the C# program with command-line arguments, you can use the dotnet command in your terminal.

dotnet run arg1 arg2 arg3

Replace arg1, arg2, and arg3 with the actual command-line arguments you want to pass.

The program will execute, and you'll see the output displaying the command-line arguments.

Keep in mind that using top-level statements is a feature available in C# 9.0 and later versions. If you're using an earlier version of C#, you'll need to define a Main method and handle command-line arguments within that method.

No comments:

Post a Comment

Hot Topics