The sequence being iterated in a foreach loop might not support indexing or know such a concept it just needs to implement a method called GetEnumerator that returns an object that as a minimum has the interface of IEnumerator though implmenting it is not required. If you know that what you iterate does support indexing and you need the index then I suggest to use a for
loop instead.
An example class that can be used in foreach
:
class Foo {
public iterator GetEnumerator() {
return new iterator();
}
public class iterator {
public Bar Current {
get{magic}
}
public bool MoveNext() {
incantation
}
}
}