What is the difference between "for" and "foreach" loop in C#?

Which one is better in performance wise and why we preferr for loop?


Giribabu
Views: 3922 | Community Opinion: 1

Tags..  C# Interview  C# Tutorial

Bookmark this page..



Ask a New Question Go to Home

Community Opinion/Answers
 

C# for loop

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is useful for iterating over arrays and for sequential processing.

Because the test of a conditional expression occurs before the execution of the loop, a for statement executes zero or more times.

C# for loop Example

class ForLoopTest
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}




foreach loop in C#

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.

C# foreach loop Example

class ForEachTest
{
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}

}


foreach loop may (not always, but depends) reduce the performance of the code. Therefore for loop is recommended.






Register or Login to Post Your Opinion