C#: Main method and its arguments args

Each time we generate a Console Application using Visual Studio, it will provide us with a template similar to below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MainApp
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

You might be wondering what is args in the Main input parameter.

As in the declaration, args is a string array.  To find out what is args, you can add 2 lines to the above template.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MainApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(args[0]);
            Console.ReadLine();
        }
    }
}

After compiling and build the program, we run the MainApp in the console.

Type in the console MainApp Hello and you will get an output similar to the screenshot below.

mainapp

When you type MainApp Hello, the word Hello will be the first argument in the args array.

Since we are printing args[0] which is the first argument, the word Hello is printed out.

 

Series Navigation<< C#: Method overloading
C#: Declaring an array >>