The foreach
statement is a way to traverse each element within an object, the advantage being that your code does not need to know the internal structure of the east. The person responsible for delivering the objects in order is the same class that you are iterating.
The only requirements to be able to use foreach
on an instance are:
- The class implements a public method called
GetEnumerator()
- The object that returns
GetEnumerator()
implements property Current
and method MoveNext()
These conditions are forced to be met if the interface IEnumerable
or IEnumerable<T>
is implemented.
There are many classes in the .NET framework that already implement these interfaces as List<T>
and Array
, you will not need to implement it yourself in most cases.