CSharp/C# Tutorial - C# Enumeration






An enumerator is a read-only, forward-only cursor over a list of values.

An enumerator is an object that implements either of the following interfaces:

System.Collections.IEnumerator
System.Collections.Generic.IEnumerator<T>

The foreach statement can iterate over an enumerable object.

Example

An enumerable object implements IEnumerable or IEnumerable<T>.

An enumerable object has a method named GetEnumerator that returns an enumerator.

IEnumerator and IEnumerable are defined in System.Collections.

IEnumerator<T> and IEnumerable<T> are defined in System.Collections.Generic.

Here is the high-level way of iterating through the characters using a foreach statement:

foreach (char c in "java2s.com"){
   Console.WriteLine (c);
}

Here is the low-level way of iterating through the characters without using a foreach statement:

using (var enumerator = "java2s.com".GetEnumerator())
while (enumerator.MoveNext()) {
    var element = enumerator.Current;
    Console.WriteLine (element);
}




Collection Initializers

You can instantiate and populate an enumerable object in a single step.

For example:

using System.Collections.Generic;
...
List<int> list = new List<int> {1, 2, 3};

For the code above to work, the enumerable object must implement the System.Collections.IEnumerable interface, and it has an Add method that has the appropriate number of parameters for the call.