Read Command Line Argruments In C#

In C#, there are many ways to get input from the user. We will look at the following ways - Command Line Arguments and Console.ReadLine. In this post, we will look at Command Line Arguments.

cheezycode-read-command-line-arguments-csharp-02



What are Command Line Arguments?


You can pass the input as arguments when you run the program. If you have noticed carefully from our previous post - Simple C# Program, Main(String[] args) method has String[] args in parenthesis. This implies - Main() method can accept array of arguments of type String. 

String is just a sequence of characters enclosed within double quotes. E.g. "THIS IS A STRING" or "CheezyCode" or "$99" or "mail@mail.com" etc. [ ] - These brackets indicate an array which is a set of items of same type. Main() only accepts array of type String. You can have int[] integerArray for storing integer values and so on for other types. Array has a special property "Length" which returns the number of elements in the array.

using System;

class Program
{
    static void Main(String[] args)
    {
        if (args.Length > 0)
        {
            Console.WriteLine("First Argument Is - " + args[0]); //PRINT FIRST ARGUMENT    
        }
        Console.Read();
    }
}

You can set the command line arguments in Visual Studio here -



This program simply reads the first argument args[0] if the length of the args array is greater than 0 and prints it on the Console. You can also loop through the argument if you expect varying number of arguments as input. We will look at Loops and Array in great detail in future posts. For now, just type and try understanding the flow of program.

Output: (Press F5)





Let us know if you have any query or concerns. Happy Reading. (refer full series here - C# Tutorial Index)



Comments

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example