How command line arguments are passed in main method in C#?


The Main() method is the entry point −

static void Main(string[] args)

The arguments array args is used to set arguments −

string[] args)

It will set the following if you add two arguments −

var args = new string[] {"arg1","arg2”}

Here is the demo code −

Example

using System;

namespace Demo {
   class HelloWorld {

      // args for command line
      static void Main(string[] args) {
         Console.WriteLine("Welcome here!");
         Console.ReadKey();
      }
   }
}

To compile a C# program by using the command-line instead of the Visual Studio IDE −

  • Open a text editor and add the above-mentioned code.

  • Save the file as helloworld.cs

  • Open the command prompt tool and go to the directory where you saved the file.

  • Type csc helloworld.cs and press enter to compile your code.

  • If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file.

  • Type helloworld to execute your program.

  • You can see the output Hello World printed on the screen.

Updated on: 21-Jun-2020

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements