Enumerations - CSharp Custom Type

CSharp examples for Custom Type:Enum

Introduction

An enumerator is a read-only, forward-only cursor over a sequence 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 iterates over an enumerable object.

An enumerable object is the logical representation of a sequence.

It is a cursor itself, but an object that produces cursors over itself.

An enumerable object either:

  • Implements IEnumerable or IEnumerable<T>
  • Has a method named GetEnumerator that returns an enumerator

The enumeration pattern is as follows:

class Enumerator   // Typically implements IEnumerator or IEnumerator<T>
{
  public IteratorVariableType Current { get {...} }
  public bool MoveNext() {...}
}

class Enumerable   // Typically implements IEnumerable or IEnumerable<T>
{
  public Enumerator GetEnumerator() {...}
}

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

                                                                                    
                                                                                      
foreach (char c in "beer")
  Console.WriteLine (c);

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

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

Related Tutorials