C# Args Loop: Foreach and For

Console screenshot

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 use a looping construct on this string array, to make more extensible programs.

Example

Note

To start, try compiling this program into an executable and then create a shortcut to it in the Windows Explorer. Change the properties of the shortcut so that at the end of the Target text, there are some arguments: these can be separated with spaces. When you then execute this program, it will loop through all these arguments and assign them to the string variable.

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

Program that uses args loops [C#]

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
Main method

More tips on using Main args. 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. Please see the separate article.

Main

Summary

The C# programming language

It is useful to use looping constructs on the args array in console programs written in the C# programming language. For some program types, you can accept as many parameters as allowed by the length of the command line, and then process them all in one program instance. This improves performance of some kinds of batch jobs; it can also simplify your programming environment considerably.

Console Programs
.NET