Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 55 / 68

Reading Command-Line Arguments

In this lesson you will learn how to read command-line arguments in C#, so values can be passed in from outside when the program runs. This is for anyone searching for "C# command-line arguments how to use".

Declaring Main(string[] args) gives you the command-line arguments through the parameter of Main. It is essential whenever you want a command-line tool whose options can be switched at run time.

The sample code checks whether any arguments were supplied with args.Length > 0, and uses a ternary operator to take args[0] as the name when there is one and fall back to "Anonymous" when there is not.

A common stumbling block for beginners is forgetting the case where no argument was supplied. Reaching straight for args[0] errors out when nothing was passed, so check args.Length first.

In real-world development, this also serves as the foundation of automation scripts that branch on the values supplied at run time.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)