TheDeveloperBlog.com


C# Args Loop: Foreach and For

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.