*
No, for and foreach is not the same. There is some difference between that and for everyone here. I mention the difference:
*
- The for loop executes a statement or statement block several times until the specified expression evaluates to false.
You must specify the boundaries of the cycle (minimum or maximum).
int j = 0; for (int i = 1; i <= 5; i++) { j = j + i ; }
The foreach statement repeats a group of built-in statements for each element of an array or collection of objects. You do not need to specify the minimum or maximum boundaries of the loop.
int j = 0; int[] myArr = new int[] { 0, 1, 2, 3, 5, 8, 13 }; foreach (int i in myArr ) { j = j + i ; }
- foreach : treats everything as a collection and reduces performance. foreach creates an instance of the counter (returned from GetEnumerator ()), and this enumerator also maintains state during the foreach loop. Then it re-calls the Next () object in the enumerator and runs your code for each object it returns.
Using the for loop , we iterate over the array in both directions, that is, from the index from 0 to 9 and from 9 to 0.
But using the for-each loop, iteration is only possible in the forward direction.
- In a variable declaration, foreach has five variable declarations (three int32 integers and two int32 arrays), while for has only three (two int32 integers and one int32 array).
When it goes into a loop, foreach copies the current array to a new one for the operation. Although it does not care about this part.
- For will use int to iterate
Foreach does not use an integer index. Instead, it is used in a collection - it returns each item in order.
coding_ninza
source share