TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Args Loop: Foreach and For

This C# example program uses the args array in the Main method. It uses foreach and for-loops.

Args loop. The Main method receives an args array.

This is an optional feature when you start a C# command line program executable. You typically can specify these in a command prompt or a shortcut. It is useful to loop over this string array.

String Array

Example. First, compile this program and then create a shortcut to it in the Windows Explorer. Change the properties of the shortcut. At the end of the Target text, add some arguments. These can be separated with spaces.

Then: When you execute this program, it will loop through all these arguments and assign them to the string variable.

C# program that uses args loops

using System;

class Program
{
    static void Main(string[] args)
    {
	// The program control flow begins here.
	// ... Use a foreach-loop.
	// ... Then use an equivalent for-loop.
	foreach (string value in args)
	{
	    Console.WriteLine("foreach: {0}", value);
	}
	for (int i = 0; i < args.Length; i++)
	{
	    string value = args[i];
	    Console.WriteLine("for: {0}", value);
	}
	Console.ReadLine();
    }
}

Output

foreach: Arg1
foreach: Arg2
foreach: Arg3
for: Arg1
for: Arg2
for: Arg3

This site has more details on using the Main method with args. This particular article only describes the usage of the foreach and for loops with the args. There are more options available in the C# language and .NET Framework.

Main

Summary. It is useful to loop over the args array in console programs written in the C# language. You can accept as many parameters as allowed by the length of the command line, and then process them all in one program instance.

And: This improves performance of some kinds of batch jobs. It can also simplify your programming environment.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf