IEnumerable And IEnumerator Interface Implementation In Different Class C#



An IEnumerable is a sequence that can be iterated over, whereas an IEnumerator is like a cursor within a sequence.

using System;
using System.Collections;

namespace CSharpCollection
{
	class ColorEnumerator : IEnumerator
	{
		string[] colors;
		int position = -1;
		public ColorEnumerator( string[] theColors ) // Constructor
		{
			colors = new string[theColors.Length];
			for ( int i = 0; i < theColors.Length; i++ )
			colors[i] = theColors[i];
		}

		public object Current // Implement Current.
		{
			get
			{
				if ( position == -1 )
				throw new InvalidOperationException();
				if ( position >= colors.Length )
				throw new InvalidOperationException();
				return colors[position];
			}
		}

		public bool MoveNext() // Implement MoveNext.
		{
			if ( position < colors.Length - 1 )
			{
				position++;
				return true;
			}
			else
				return false;
		}

		public void Reset() // Implement Reset.
		{
			position = -1;
		}
	}
	
	class Spectrum : IEnumerable
	{
		string[] Colors = { "violet", "blue", "cyan", "green", "yellow", "orange", "red" };
		public IEnumerator GetEnumerator()
		{
			return new ColorEnumerator( Colors );
		}
	}

	class Program
	{
		static void Main()
		{
			Spectrum spectrum = new Spectrum();
			foreach ( string color in spectrum )
			Console.WriteLine( color );
		}
	}	
}

0 Comment's

Comment Form