Loop, string array. The for and foreach loops can iterate over string arrays. We must choose between these 2 loops in many C# programs.
The foreach-loop has the simplest syntax, but this comes with some limitations. The for-loop uses an iteration variable, which can lead to complexity and errors.
Example. In most programs you have a string array, you will need to loop over the individual string elements. The simplest way of looping over the elements is with foreach.
Note The code is a complete C# console program. The string array is initialized and 4 values are inserted into it.
Next A foreach-loop iterates over each string in the array. The 4 values are printed to the console.
using System;
string[] array = new string[4];
array[0] = "one";
array[1] = "two";
array[2] = "three";
array[3] = "four";
// Loop over strings.
foreach (string value in array)
{
Console.WriteLine(value);
}one
two
three
four
Example 2. We use the for-loop to accomplish the same task. The syntax is different and for-loops have some advantages. There is usually not a significant difference in performance.
Here This example initializes a string array with 4 elements with Spanish numbers.
Then We loop over the string array with the for-loop construct, going from start to end. The loop starts at 0.
Finally The second loop walks over the strings backwards. It starts at the last index, which is one less than the length. It decrements.
using System;
string[] array = new string[4];
array[0] = "uno";
array[1] = "dos";
array[2] = "tres";
array[3] = "cuatro";
// Loop over strings.
for (int i = 0; i < array.Length; i++)
{
string value = array[i];
Console.WriteLine(value);
}
// Loop over strings backwards.
for (int i = array.Length - 1; i >= 0; i--)
{
string value = array[i];
Console.WriteLine(value);
}uno
dos
tres
cuatro
cuatro
tres
dos
uno
There is not a significant performance difference between most for and foreach-loops. Here is a short summary of the 2 different looping constructs.
Note Foreach has simpler syntax and makes fewer typos likely. You can use custom enumerators. You can change the internal looping mechanism.
Note 2 For is usually equal in speed or faster. You can check the previous or next elements. You can loop in reverse.
We looped over string arrays in the C# language. The code to loop over your arrays is usually similar to this, except the type declarations will be different.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 28, 2023 (edit).