Saturday, July 3, 2010

Using IEnumerable and IEnumerator interfaces.

in this example I demonstrate how to use IEnumerable interface and the GetEnumerator function and how to use IEnumerator with Movenext(), Reset() and the Current property
in order to to loop through a class content using foreach ...

using System;
using System.Collections;

namespace ConsoleApplication5
{


class data
{
string name;
int age;

public data()
{

}
public data(string name, int age)
{

this.name = name;
this.age = age;
}

public string _name
{
get
{
return name;
}
}
public int _age
{
get
{
return age;
}
}

}
class people : IEnumerator, IEnumerable
{

public IEnumerator GetEnumerator()
{
return x.GetEnumerator();
}


internal int pos = 0;
data[] x = new data[4];

public people()
{

x[0] = new data("Ali", 32);
x[1] = new data("mohammed", 22);
x[2] = new data("wael", 24);
x[3] = new data("slah", 34);
}
public object Current
{
get
{
return x[pos];
}
}

public bool MoveNext()
{

if (pos <= x.Length)
{
++pos;
return true;

}
else
return false;
}

public void Reset()
{
Console.WriteLine("Reset...");
pos = 0;
}

}


class Program
{
static void Main(string[] args)
{

people p = new people();
foreach (data d in p)
{
Console.WriteLine(d._name + " " + d._age.ToString());
}
}
}
}

No comments:

Post a Comment