Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: for verses foreach [duplicate]

Tags:

c#

.net

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.


1 Answers

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;
}
like image 136
MGZero Avatar answered Feb 25 '26 11:02

MGZero