I have a foreach loop that needs converting to a for or while loop. My loop looks like this:
foreach (Item item in Items)
{
// some stuff
}
What is the equivalent for or while loop?
I think I need to use GetEnumerator to get an IEnumerator<Item>, but I don’t know how to use it properly. Items isn’t a list, otherwise I’d use indexing.
In the simplest case(no disposing etc.) you can use:
For the exact rules check the C# specification 8.8.4 The foreach statement.
(Quoted from the C# Language Specification Version 4.0)
The types using here are: “a collection type
C, enumerator typeEand element typeT“.Eis the return type ofGetEnumerator, and not necessarilyIEnumerator<V>sinceforeachuses duck typing. The spec also describes a number of corner cases and how to infer these types, but those details are probably not relevant here.In C# 5 the declaration of
vwill be moved into thewhileloop to get more intuitive closure semantics.