Ienumerator

J

juan

hi i have a teachers class where i want the user to enter a few teachers and
iterate thru them.
In the main i get an error

System.Collections.IEnumerator' does not contain a definition for 'Length'
why is that?
is this approach right? I want to develop an OO App. so is this approach
right?



public class PermTeacher: IEnumerable
{
public ArrayList arrTeachers =null;
string name =null;
private IEnumerator e;
public PermTeacher()
{
}
public IEnumerator GetEnumerator()
{
throw new NotSupportedException();
}
public void addTeachers(string nm)
{
IEnumerator e;
PermTeacher p =new PermTeacher ();
p.name = nm;
arrTeachers = new ArrayList();
arrTeachers.Add (p);
//if (arrTeachers !=null)
e=this.arrTeachers.GetEnumerator();
}
public IEnumerator getTeachers()
{
return e;
}
}





static void Main()
{
Teachers.PermTeacher p = new Prac1.Teachers.PermTeacher();
p.addTeachers("teacher1");
IEnumerator en = p.getTeachers();
for (int i =0;i< en.Length ;i++) //Gives me an error here.
{
}
Application.Run(new Form1());
}
 
D

Daniel O'Connell [C# MVP]

juan said:
hi i have a teachers class where i want the user to enter a few teachers
and
iterate thru them.
In the main i get an error

System.Collections.IEnumerator' does not contain a definition for 'Length'
why is that?
is this approach right? I want to develop an OO App. so is this approach
right?



public class PermTeacher: IEnumerable
{
public ArrayList arrTeachers =null;
string name =null;
private IEnumerator e;
public PermTeacher()
{
}
public IEnumerator GetEnumerator()
{
throw new NotSupportedException();
}
public void addTeachers(string nm)
{
IEnumerator e;
PermTeacher p =new PermTeacher ();
p.name = nm;
arrTeachers = new ArrayList();
arrTeachers.Add (p);
//if (arrTeachers !=null)
e=this.arrTeachers.GetEnumerator();
}
public IEnumerator getTeachers()
{
return e;
}
}





static void Main()
{
Teachers.PermTeacher p = new Prac1.Teachers.PermTeacher();
p.addTeachers("teacher1");
IEnumerator en = p.getTeachers();
for (int i =0;i< en.Length ;i++) //Gives me an error here.
{
}
Application.Run(new Form1());
}

IEnumerator is designed to iterate over a series of values without you
having to know anything about ordering or length(this isn't always ideal,
but it works much of the time). Its much more common to use the foreach
construct(Look it up on msdn) to access enumerators

If you want to write code yourself, you instead would use a while loop,
something like...

while (en.MoveNext()) {

//do your work here

}
(I think...havn't written one by hand in a long time, I could be making a
mistake)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top