Mega Code Archive

 
Categories / C# Book / 03 Collections
 

0341 IEnumerable and IEnumerator

IEnumerator defines the protocol for traversable or enumerable collections. Its declaration is as follows: public interface IEnumerator { bool MoveNext(); object Current { get; } void Reset(); } IEnumerable is IEnumerator provider: public interface IEnumerable { IEnumerator GetEnumerator(); } The following example illustrates how to use IEnumerable and IEnumerator: using System; using System.Collections; class Sample { public static void Main() { string s = "rntsoft.com"; IEnumerator rator = s.GetEnumerator(); while (rator.MoveNext()) { char c = (char)rator.Current; Console.Write(c + "."); } } } The output: r.n.t.s.o.f.t...c.o.m. C# provides a shortcut: foreach statement. using System; using System.Collections; class Sample { public static void Main() { string s = "Hello"; // The String class implements IEnumerable foreach (char c in s) Console.Write(c + "."); } } The output: H.e.l.l.o.