Passing Command-Line Arguments in C#: Providing Input to Console Applications

Learn how to pass command-line arguments to your C# console applications. This tutorial explains how to access command-line arguments through the `args` parameter in the `Main` method, providing a flexible method for configuring and controlling your applications without requiring user interaction.



Passing Command-Line Arguments in C#

Command-line arguments are values passed to a C# program when it's executed from the command line. This is a very useful way to provide input to a program without requiring an interactive user interface. They're often used for configuration, specifying input files, or setting various options.

Accessing Command-Line Arguments

In C#, command-line arguments are accessible through the `args` parameter in your `Main` method. The `args` parameter is a string array containing each argument as a separate element.

Example: Displaying Command-Line Arguments


using System;

public class CommandLineArgsExample {
    public static void Main(string[] args) {
        Console.WriteLine($"Number of arguments: {args.Length}");
        Console.WriteLine("Arguments:");
        foreach (string arg in args) {
            Console.WriteLine(arg);
        }
    }
}

To run this code from the command line, you'd compile it (e.g., `csc MyProgram.cs`) and then execute it, providing arguments separated by spaces (e.g., `MyProgram.exe arg1 arg2 arg3`). The output shows the number of arguments provided and the value of each argument.