The foreach loop in C# executes a statement or a block of statements for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable
The array syntax is as follows:
- foreach (<baseType> <name> in <array>)
In the code below we have declared a variable called friendNames that is an array of strings, as indicated by string[]. We have used object initialization syntax to immediately initialize the array. In the foreach() loop the basetype is string. the name is friendName. The array is friendNames.
class Program { static void Main(string[] args) { string[] friendNames = { "Jack", "Kevin", "Sally" }; Console.WriteLine("Here are {0} of my friends:", friendNames.Length); foreach (string friendName in friendNames) { Console.WriteLine(friendName); } Console.ReadKey(); } }
foreach gives you read-only access to the array contents, so you can’t change the values of any of the elements. In other words, if you try to assign a literal to any of the elements in the array within the foreach() loop, compilation fails.
Class Objects
We have another post where we create a Customer class and create a couple of objects, create a list of Customers that we iterate through using a foreach loop to display some properties. The code is in the post C# Lists of Class Objects.