This would be question from c# beginner. When I create console application I get Main method with parameter args as array string. I do not understand how t
The runtime splits the arguments given at the console at each space.
If you call
myApp.exe arg1 arg2 arg3
The Main Method gets an array of
var args = new string[] {"arg1","arg2","arg3"}
The main method of the runtime engine looks something like int main(int argc, char *argv[])
, where argc is a count of the number of arguments and argv is an array of pointers to each. The runtime engine converts this into a form that is more natural to c#.
Prior to that main method being called, everything is in assembly language. It has access to the command line arguments (because the operating system makes that available to every process that starts), but that assembly language needs to convert a single string of the full command line into multiple substrings (using whitespace to separate them) before it's ready to pass them into main().
How is main called?
When you are using the console application template the code will be compiled requiring a method called Main in the startup object as Main is market as entry point to the application.
By default no startup object is specified in the project propery settings and the Program class will be used by default. You can change this in the project property under the "Build" tab if you wish.
Keep in mind that which ever object you assign to be the startup object must have a method named Main in it.
How are args passed to main method
The accepted format is MyConsoleApp.exe value01 value02 etc...
The application assigns each value after each space into a separate element of the parameter array.
Thus, MyConsoleApp.exe value01 value02 will mean your args paramter has 2 elements:
[0] = "value01"
[1] = "value02"
How you parse the input values and use them is up to you.
Hope this helped.
Additional Reading:
Creating Console Applications (Visual C#)
Command-Line Arguments (C# Programming Guide)
Every managed exe has a an entry point which can be seen when if you load your code to ILDASM. The Entry Point is specified in the CLR headed and would look something like this.
All answers are awesome and explained everything very well
but I just want to point out different way for passing args to main method
in visual studio
like this image
and happy knowing secrets
The Main method is the Entry point of your application. If you checkout via ildasm
then
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
This is what helps in calling the method
The arguments are passed as say C:\AppName arg1 arg2 arg3