foreach:
The foreach statement is just like a for-loop to executes a block of embedded statements on each element in an array or a collection of items. foreach is a different kind of looping constructs in C# programming that doesn’t includes initialization, termination and increment/decrement characteristics. It uses collection to take value one by one and then processes them.
The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for-loop.
The embedded statements continue to execute for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the foreach block.
At any point within the foreach block, we can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword.
A foreach loop can also be exited by the goto , return, or throw statements.
Syntax:
We use the following syntax to use foreach loop in C#:
foreach( Data-Type Variable-name in array-variable-name )
{
//Foreach body:
}
Example:
Let's have an example to know, how to use foreach statement: this is very simple and conceptual example to know how exactly foreach keyword work.
/*Example: Foreach statement: InfoBrother:*/
using System;
namespace for_each
{
class Program
{
static void Main(string[] args)
{
string[] name = new string[5]; //array of type string declare:
//store values in array element:
name[0] = "Omar";
name[1] = "InfoBrother";
name[2] = "Taimur";
name[3] = "Usman";
name[4] = "Khizar";
//display values using foreach loop:
foreach(string show in name)
{
Console.WriteLine("Hello Mr " + show);
}
Console.ReadKey();
}
}
}
foreach Loop:
Hello Mr Omar
Hello Mr InfoBrother
Hello Mr Taimur
Hello Mr Usman
Hello Mr Khizar
for-loop Vs foreach:
/*Example: For loop statement: InfoBrother:*/
using System;
namespace for_each
{
class Program
{
static void Main(string[] args)
{
int[] number = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
for (int i = 0; i < number.Length; i++) //for loop:
{
System.Console.WriteLine(number[i]);
}
System.Console.WriteLine();
Console.ReadKey();
}
}
}
/*Example: Foreach statement: InfoBrother:*/
using System;
namespace for_each
{
class Program
{
static void Main(string[] args)
{
int[] number = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in number) //foreach loop:
{
System.Console.WriteLine(element);
}
System.Console.WriteLine();
Console.ReadKey();
}
}
}
“
In Above i write some code using for-loop and then foreach loop. Both codes will produce the same result. foreach is used on top of collections to traverse while for can be used on anything for the same purpose.