In the C# programming language, the command line arguments are used to pass the value from the user or programmer to the program at the time of execution. It is a straightforward method for passing a message between the user and the main method of the program. The values are passed through the command line, known as the command line arguments.
Syntax of Command Line Arguments
It has the following syntax.
Static void main (string[] args)
{
// block of code
}
In the above syntax,
- Static: It represents that the Main method can execute without any object.
- string : It is the type of arguments that is passed to the method.
- Args: It represents the arguments which is defined by the user.
Command-Line Arguments Example in C#
Let's consider an example that calculates the sum of two numbers provided as arguments.
Example
using System;
namespace CSharpProgram
{
class Program
{
// Main Method
static void Main( string[] args ) // string type parameters
{
Console.WriteLine(" The number of input is "+args.Length );
Console.WriteLine(" The Supplied Arguments are: ");
foreach (object o in args )
{
Console.WriteLine(obj);
}
}
}
}
Run this program by employing the subsequent commands.
Compile: csc program.cs
Execute: Program.exe Hi there, how are you?
Output:
Argument length: 5
Supplied Arguments are:
Hi
there,
how
are
you.
Explanation:
In this illustration, we display the quantity of parameters by utilizing args.Length, followed by iterating through each parameter sequentially using a foreach loop. Subsequently, the output is showcased using the Console.WriteLine method.
How do Command Line Arguments Work in C#?
In C# programming, command line arguments are transmitted to the program via the main function during execution from the command line interface. These arguments are retrievable within the main function.
Passing Arguments to the Main Method
In C#, the parameters are provided to the main function via command-line arguments when the program is executed. The Main function acts as the starting point of a C# application and can receive a string array (string args) as an input to access these arguments within the C# code.
Passing Arguments Example in C#
Let's consider an example to demonstrate how to pass arguments to the main method.
Example
using System;
class Program
{
static void Main( string[] args )
{
Console.WriteLine(" The number of arguments passed: " + args.Length );
for ( int i = 0; i < args.Length; i++ )
{
Console.WriteLine(" The Argument " + (i + 1) + ": " + args[i] );
}
}
}
Output:
The number of arguments passed: 0
Explanation:
In this instance, we will illustrate the utilization of command line parameters. Within the main function, an array string args is declared to hold the input values provided during program execution. Subsequently, the script displays the overall count of arguments, followed by iterating through each argument using a for loop in conjunction with the Console.WriteLine method.
Factorial Program using Command Line Arguments in C#
Let's consider an example to compute factorial numbers using command line arguments in C#.
Example
using System;
using System.IO;
using System.Collections.Generic;
namespace ConsoleApp4
{
class Program
{
public static void Main(string[] args)
{
int num;
int fact;
try
{
if (args.Length == 0)
{
Console.WriteLine("Enter a number to calculate its factorial " + "its fact");
return;
}
if(args.Length > 1)
{
Console.WriteLine("Enter a number for your choice");
return;
}
Console.WriteLine("The number entered is: " + args[0]);
num = Convert.ToInt32(args[0]);
fact = num;
//determine factorial
for( int i = num - 1; i >= 1; i-- )
{
fact = fact * i;
}
Console.WriteLine("The factorial of {0} is {1}", args[0], fact);
Console.ReadLine();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Output:
Enter a number to calculate its factorial: 5
The factorial of 5 is: 120
Explanation:
In the aforementioned illustration, initially, it validates the presence of the given input. In case the input is absent, it prompts for a numerical value. Upon confirming a valid input, the script transforms it into an integer and computes the factorial employing a loop. The outcome is displayed utilizing the Console.WriteLine method.
Program: Check Even or Odd Number via C# Command Line Arguments.
Let's consider an example to determine if a number is even or odd by utilizing C# command line arguments.
Example
using System;
using System.IO;
using System.Collections.Generic;
namespace Console
{
class Program
{
public static void Main( string [] args )
{
List<int> even_Array = new List<int>();
List<int> odd_Array = new List<int>();
try
{
if ( args.Length == 0 )
{
Console.WriteLine("Enter numbers your choice ");
return;
}
for ( int i = 0; i < args.Length; i++ )
{
if ((Convert.ToInt32(args[i]) % 2) == 0)
{
even_Array.Add(Convert.ToInt32(args[i]));
}
else
{
odd_Array.Add(Convert.ToInt32(args[i]));
}
}
// printing all the numbers entered
Console.WriteLine("The entered number is ");
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine(args[i]);
}
Console.WriteLine("\n The Even numbers are ");
for (int i = 0; i < even_Array.Count; i++)
{
Console.WriteLine(even_Array[i]);
}
Console.WriteLine("\n The Odd numbers are ");
for ( int i = 0; i < odd_Array.Count; i++ )
{
Console.WriteLine(odd_Array[i]);
}
Console.ReadLine();
}
catch(Exception ex)
{
Console.WriteLine( ex.Message );
}
}
}
}
Output:
10 7 4 3 12 9
Numbers entered:
10
7
4
3
12
9
Even numbers:
10
4
12
Odd numbers:
7
3
9
Explanation:
In this instance, we are extracting various numerical values from the command line and categorizing them into two groups: even and odd numbers. Initially, we validate the presence of any input arguments. Should no arguments be present, a prompt is displayed requesting the entry of a number. Subsequently, a for loop is employed to iterate through the arguments, converting each one into an integer, and determining its parity as even or odd. Ultimately, the Console.WriteLine method is utilized to display the resulting output.
Conclusion
Command line arguments serve as a means to transmit values from either the user or developer to the program. This straightforward approach facilitates communication between the main method and the user. The data is transferred through the command line, referred to as command line arguments.
C# Command Line Arguments FAQs
1) What are the Command Line Arguments in C#?
In the C# programming language, command line arguments serve the purpose of transferring values from the user or developer to the program. This method facilitates direct communication between the user and the main method. The information is transmitted via the command line, commonly referred to as command line arguments.
The data type of the Command Line Arguments in C# is an array of strings.
In C#, the command line arguments are stored within the args parameter in the main function. The syntax is as illustrated below.
static void main (string[] args )
Therefore, the data type of the command line parameters is of the string type.
Can a foreach loop be utilized to iterate through the arguments?
Yes, we have the option to iterate over arguments using the foreach loop.
foreach (string arg in args)
{
Console.WriteLine(arg);
}
4) How to access command line arguments in C#?
In C#, the arguments are accessed by their index.
Console.WriteLine(args[0]); // The first argument
Console.WriteLine(args[1]); // The second argument
5) What does args.Length represented in C#?
The args.Length property signifies the overall size of the argument passed to the program.