Possible Duplicate:
For vs Foreach loop in C#
Is one better than another?
Seems I've heard that a for loop has less overhead than a foreach, but I've yet to see the proof of this.
One being "better" than the other depends on your application. Are you just reading a data structure? Are you writing to a data structure? Are you not even using any sort of data structure and just doing some math?
They each have their own uses. The for each loop is usually used for reading things from a data structure (array, linked list etc). For example.
foreach(myClass i in myList)
{
int x = i.getX();
console.writeline(x);
}
Where the for loop can be used to do the above, among other things such as update a data structure entry.
for (int i = 0; i < myList.count(); i++)
{
myList[i].x += i * 80;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With