TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Main Args Examples

This C# example program uses parameters in the Main entry point method.

Main, Args. Every program has a Main entry point.

In Main, we access a string array called args. This array is populated with command-line arguments from the operating system. This makes it possible to configure programs with minimal complexity.

String Array

Example. When you create a new console application in the C# language using Visual Studio, you will get a Main method with a signature similar to the one shown here. It will have a string[] args parameter and void return type.

ArgsVoid

Also: You can use a Main method that returns an int or that receives no parameters if you want to.

ReturnInt

Next: This program shows how the command-line parameters are received from a Windows command line.

C# program that receives command-line arguments

using System;

class Program
{
    static void Main(string[] args)
    {
	if (args == null)
	{
	    Console.WriteLine("args is null"); // Check for null array
	}
	else
	{
	    Console.Write("args length is ");
	    Console.WriteLine(args.Length); // Write array length
	    for (int i = 0; i < args.Length; i++) // Loop through array
	    {
		string argument = args[i];
		Console.Write("args index ");
		Console.Write(i); // Write index
		Console.Write(" is [");
		Console.Write(argument); // Write string
		Console.WriteLine("]");
	    }
	}
	Console.ReadLine();
    }
}

Output

"C:\ConsoleApplication1.exe" a b c
args length is 3
args index 0 is [a]
args index 1 is [b]
args index 2 is [c]

"C:\ConsoleApplication1.exe" a                 b           c
args length is 3
args index 0 is [a]
args index 1 is [b]
args index 2 is [c]

"C:\\ConsoleApplication1.exe" 
args length is 1
args index 0 is []

"C:\ConsoleApplication1.exe" "Literal      test "
args length is 1
args index 0 is [Literal      test ]

Main can be defined in any valid class name. Note that you must have a class enclosing all methods in your C# program. Upon startup the Main method is executed. It then tests for a null array argument—this is never reached.

Class

Then: It prints the array length and then writes the arguments as strings with Console.WriteLine.

Console.WriteLine

Note: The "Output" section of the example shows possible command lines and the program's actual output.

Whitespace. More than one whitespace is discarded when separating the arguments. So if you separate parameters by two spaces, there is no difference from separating with one space. But with the string literal syntax, enclosed whitespace is retained.

Tip: If you want to preserve whitespace on the command line, use the quotation marks around your parameter.

Null. In my testing, you will not encounter a null parameter array in the Main entry point. So if you execute a program with no command-line parameters, you will not receive a null string array reference in the Main method.

Null

However, if incorrect parameters are likely, it is best to wrap the Main entry point with try, catch and finally blocks. This ensures the best possible execution paths are taken. If a step is critical, put it in a finally block.

TryCatchFinally

Signature. You can change the signature of the Main method in your program and the program will still compile and execute correctly. You can demand that the Main method return an int. This tells the operating system the program's result.

Tip: It is also useful to omit the string[] args parameter array entirely when not needed.

Also: This site almost always omits the parameter array to shorten the example programs and improve clarity.

Shortcut. In Windows, you can open your program's Release or Debug directory and create a shortcut to your application and specify command-line parameters in that shortcut. Right-click on the EXE file and select Create Shortcut.

Then, in the "Target" text box in the Shortcut Properties window, append the command-line arguments after the file name. When you click on the shortcut, these strings will be put into the string[] args array at runtime in the Main method.

Summary. We saw the exact behavior of the Main entry point when used with an args string array. We saw examples of calling the Main method from the Windows operating system with shortcuts. We noted how whitespace in the command-line is handled.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf