After a google search i found many answers opposing other answers which complicated things even more
In the case of arrays in particular, there is no performance difference. Foreach is a bit less typing, so if you don’t need the index for other reasons, just use foreach. Also since these questions can be subtle, and people can be misinformed due to bad, our out of date information, the best thing to do is learn to use benchmarkdotnet (its a nuget library, google it) so you can quickly run your own experiments to know what is true, for sure, with your particular work loads on your particular hardware and platform.
Sometimes these things change with new framework versions, etc.
I believe i read in a book (the c# player guide 3rd edition) that foreach tend to be slower
It really depends on what you want to do.
For loops are technically more efficient since they don’t make use of an iterator, which requires additional memory and field updating. Note that this is unlikely to ever matter.
Additionally, if you want to make use of the index number of the data you’re seeking, a for loop will be a better choice since you’ll have a number that corresponds to the index already at hand.
On the other hand, if you’re doing a bunch of stuff with the item you’re accessing it can be easier/nicer to simply refer to the item by a single name rather than “arrayname[index]” each time. In that case a foreach loop will provide a much better experience.
Ultimately the answer is going to depends heavily on what is specifically being done as well as somewhat on personal preference.
foreach on arrays is special cased by the compiler and is just as efficient. This is not the case on lists.
Depending on the context you can also use the Linq methods Select, Where, Aggregate etc.
You can not modify the elements of the list you are processing with a foreach, the iteration variable is read only. Only in that cases I use a for instead.
to add on to what others have provided:foreach works on any type that has a GetEnumerator
method that has a Current
and MoveNext
on it. As such, what it does is iterate, meaning, it calls MoveNext and Current to get the next item into your variable (except for arrays).
Now, what should you actually write? Whatever looks most readable. Saving a few nano-seconds isn’t going to actually do anything. If you need an index, use for
, otherwise, just use foreach
.
C# devs
null reference exceptions