In this post I actually created a simple program using C# that implements IEnumerator and IEnumerable.
So if you are interested let's get started....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace IEnumSamp
{
class Program
{
static void Main(string[] args)
{
clsEmployee[] emp = new clsEmployee[]
{ new clsEmployee("rhian", "calzado", 30),
new clsEmployee("jin", "necesario", 29),
new clsEmployee("rouie", "andes", 30)
};
EmployeeCollection myEmployees =
new EmployeeCollection(emp);
IEnumerator EmpEnum = myEmployees.GetEnumerator();
while (EmpEnum.MoveNext())
{
Console.WriteLine(((clsEmployee)(EmpEnum.Current)).FirstName);
}
foreach (clsEmployee emp_ in myEmployees)
{
Console.WriteLine(emp_.ToString());
}
}
}
}
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace IEnumSamp
{
public class clsEmployee
{
private string strFirstName;
private string strLastName;
private int intAge;
public clsEmployee(string fname, string lname, int age)
{
this.strFirstName = fname;
this.strLastName = lname;
this.intAge = age;
}
public string FirstName
{
get
{
return this.strFirstName;
}
}
public string LastName
{
get
{
return this.strLastName;
}
}
public int Age
{
get
{
return this.intAge;
}
}
public override string ToString()
{
return "Fullname: " + this.strLastName + ", " + this.strFirstName + " Age: " +this.intAge.ToString ();
}
}
public class EmployeeCollection : IEnumerable
{
private clsEmployee[] emp_;
public EmployeeCollection(clsEmployee[] emp)
{
if (emp.GetType() == typeof(clsEmployee[]))
{
emp_ = emp;
}
else
throw new ArgumentException("invalid type");
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return (IEnumerator)new EmployeeEnum(emp_);
}
#endregion
}
public class EmployeeEnum : IEnumerator
{
private clsEmployee[] empList = null;
public EmployeeEnum(clsEmployee[] emp)
{
if (emp.GetType() == typeof(clsEmployee[]))
{
empList = emp;
}
else
throw new ArgumentException("invalid type");
}
private int intPosition=-1;
#region IEnumerator Members
public object Current
{
get
{
if (intPosition < 0)
throw new InvalidOperationException();
if (intPosition > empList.Length)
throw new InvalidOperationException();
return empList[intPosition];
}
}
public bool MoveNext()
{
this.intPosition++;
if (this.intPosition >= empList.Length)
return false;
else
return true;
}
public void Reset()
{
this.intPosition = -1;
}
#endregion
}
}




1 comments:
Good article
We can submit .net related article links on http://www.dotnettechy.com to increase traffic
Post a Comment