Tuesday, June 17, 2008

Hi Mom, I'm on MSDN - System.Collections.IEnumerable

I was recently implementing the IEnumerable and IEnumerator interface and needed to check out the documentation on MSDN. I thought the example could use some sprucing up since it used an array that has a fixed size and had two separate classes for the interfaces. Here are the updates:

  1. Implemented both IEnumerable and IEnumerator interfaces into one class.
  2. Useed a generic list instead of an array which has a fixed size.
  3. Added an indexer.

IEnumerable Interface

http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx

Source

using System;
using System.Collections;
using System.Collections.Generic;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Person> peopleArray = new List<Person>()
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};

People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);

Person p2 = peopleList[1]; //Jim Johnson
Console.WriteLine(p2.firstName + " " + p2.lastName);
}
}

public class Person
{
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}

public string firstName;
public string lastName;
}

public class People : IEnumerable, IEnumerator
{
private List<Person> people;
int position = -1;
public People(List<Person> list)
{
people = list;
}

public Person this[int indexer]
{
get { return people[indexer]; }
set { people[indexer] = value; }
}

public bool MoveNext()
{
position++;
return (position < people.Count);
}

public void Reset()
{
position = -1;
}

public object Current
{
get
{
try
{
return people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}

public IEnumerator GetEnumerator()
{
return new People(people);
}
}
}

No comments:

Post a Comment