#21 – C# Main Method Parameters or Command-Line Arguments

The parameter of the Main method is a String array that represents the command-line arguments.

using System;

class Program
{
   static void Main(string[] args)
   {
        if (args.Length != 2)
        {
            Console.WriteLine("Invalid parameters. You have to pass two parameters like: dotnet run 10 20");

            return;
        }

        Console.WriteLine("You have input two parameters: ");
        foreach (var item in args)
        {
            Console.Write($" {item} ");
        }

        Console.WriteLine();

    }
}

Run the console application with following command:

$ dotnet run p1

you will get result:

Invalid parameters. You have to pass two parameters like: dotnet run 10 20

Run with following command:

$ dotnet run p1 p2

you will get result:

You have input two parameters: 
 p1  p2 

Key Point

In case you want to supply arguments that are in conflict with the arguments of the dotnet run command, you can use two dashes (--) like:

dotnet run -- p1 p2

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.