Modify values of arrays and the foreach loop
In this article we will discuss how to change values in an array. To do this, we have to overwrite the position we want to change with a different value than the one we have initialized. Let’s take a look at this.
Example: Change values in array
class Program { public static void Main(string[] args) { string[] animalsArray = { "Dog", "Cat", "Mouse", "Elephant" }; Console.WriteLine("Before changing"); Console.WriteLine(animalsArray[0]); Console.WriteLine(animalsArray[1]); animalsArray[0] = "Monkey"; animalsArray[1] = "Horse"; Console.WriteLine("After changing"); Console.WriteLine(animalsArray[0]); Console.WriteLine(animalsArray[1]); Console.ReadLine(); } }
Here we created an Array os String in which we entered 4 animals. Then we print out the animals in our array. Afterwards we overwrite some of them and print out again.
As an output we receive:
Before changin
Dog
Cat
After changing
Monkey
Horse
Example for a Foreach Loop in CSharp
class Program { public static void Main(string[] args) { string[] animalsArray = { "Dog", "Cat", "Mouse", "Elephant" }; foreach (string index in animalsArray) { Console.WriteLine(index); } Console.WriteLine("Overwriting values ------"); animalsArray[0] = "Bug"; animalsArray[2] = "Lion"; foreach (string index in animalsArray) { Console.WriteLine(index); } Console.ReadLine(); } }
Now we can do it much more automated. We use a foreach loop. It allows us to run through the whole array and work with the values aftewards.
The syntax is the following
foreach (Data type Variablename in Arrayname)
{
// what to do with the elements in the array
}