How exactly is string[] args
populated in a C# Main method?
For instance, is white space stripped? Are any of the elements ever empty string or null? How are single and double quotes handled?
MSDN doesn't explain how and merely says
The parameter of the Main method is a String array that represents the command-line arguments
String[] args means an array of sequence of characters (Strings) that are passed to the "main" function. This happens when a program is executed. Example when you execute a Java program via the command line: java MyProgram This is just a test. Therefore, the array will store: ["This", "is", "just", "a", "test"]
The string[] args is a variable that has all the values passed from the command line as shown above. Now to print those arguments, let's say we have an argument, “One” − Console. WriteLine("Length of the arguments: "+args. Length); Console. WriteLine("Arguments:"); foreach (Object obj in args) { Console.
When you run Java program, by right click on Java class with main method, it creates a Run Argument for that class. By the way, you can write your String args[] as String[] args as well, because both are valid way to declare String array in Java.
String [] arguments is a java array of String objects. This means that the main function expects an array of Strings. This array of strings typically holds all command line parameter arguments passed in when the program is run from the command line.
When you start a process, you can pass a string as your argument. How those are arranged and split up is entirely up to you.
So if using the Windows command line, you ran:
myexe.exe "Hello World" Joe Bloggs
Your array would contain:
{"Hello World", "Joe", "Bloggs"}
But it's only split up in that particular way (notice the quotes around Hello World are removed) because the .Net framework is automatically parsing it for you.
I believe the args given to Main are those returned by Environment.GetCommandLineArgs() after removing the first of the list. MSDN describes the suprisingly complex logic concerning backslashes:
Command line arguments are delimited by spaces. You can use double quotation marks (") to include spaces within an argument. The single quotation mark ('), however, does not provide this functionality.
If a double quotation mark follows two or an even number of backslashes, each proceeding backslash pair is replaced with one backslash and the double quotation mark is removed. If a double quotation mark follows an odd number of backslashes, including just one, each preceding pair is replaced with one backslash and the remaining backslash is removed; however, in this case the double quotation mark is not removed.
Thanks to Christian.K in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With