Reading command line arguments

Reading command line arguments

How to:

Here’s how to gobble up those command line arguments:

using System;

class Program
    static void Main(string[] args)
        Console.WriteLine("You've entered the following arguments:");
        foreach (string arg in args)

If you run your program like this: yourapp.exe arg1 arg2 arg3, expect the output:

You've entered the following arguments:

Deep Dive

The tradition of command line arguments harks back to the dawn of computing, allowing early software to be flexible. In C#, args is a string array in Main() holding the arguments passed. Alternatives? Sure, there are libraries such as CommandLineParser that beef up capabilities, but for many tasks, args is your quick and dirty friend.

Under the hood, a C# app starts with Main(). When you call your app from a command line or script, the operating system slaps the arguments into an array and passes it to Main(). Easy peasy.

Got a complex app? Maybe you need to parse flags, options and values? That’s where libs shine with more control and less boilerplate code than raw args parsing. But for simple input? args all the way.

See Also