enumerators

  • Thread starter Thread starter juan
  • Start date Start date
J

juan

hi i have an arraylist that has doctor objects with various properties,
members and methods.

i want to enumerate this arraylist object.
but i dont understand how.
this is what i have done


ArrayList arrDoctors = Doctors.GetAllDoctors();
for (int cnt =0;cnt<1; cnt++)
{
Doctor p = (Doctor) arrDoctors[cnt];
Messagebox.show (p.Name);
//many other properties
}
what is the advantage of enumerators over what i have done?

and how do i implement them for my doctors array
 
Hi juan,

foreach (Doctor p in Doctors.GetAllDoctors())
{
Messagebox.show (p.Name);
}

The advantage is more readable code.
 
The only advantage is that you'll be using a foreach statement.
But you'll still have to cast the Current object to a Doctor.

In v 2.0 of the Framework, the generics are gonna make our lifes much easier
in cases like yours, but for now, you can't use 'em.


Cheers,
Branimir
 
but dont i have to derive a class from IEnumerable interface?


Miha Markic said:
Hi juan,

foreach (Doctor p in Doctors.GetAllDoctors())
{
Messagebox.show (p.Name);
}

The advantage is more readable code.

--
Miha Markic [MVP C#] - RightHand .NET consulting & software development
miha at rthand com
www.rthand.com

juan said:
hi i have an arraylist that has doctor objects with various properties,
members and methods.

i want to enumerate this arraylist object.
but i dont understand how.
this is what i have done


ArrayList arrDoctors = Doctors.GetAllDoctors();
for (int cnt =0;cnt<1; cnt++)
{
Doctor p = (Doctor) arrDoctors[cnt];
Messagebox.show (p.Name);
//many other properties
}
what is the advantage of enumerators over what i have done?

and how do i implement them for my doctors array
 
juan said:
but dont i have to derive a class from IEnumerable interface?

Doctors itself doesn't have to - Doctors.GetAllDoctors() returns an
ArrayList, and *that* can be enumerated.
 
Hi Juan,

You can directly enumerate an "ArrayList" with *foreach* construct.

You will get the advantage of enumerator when you implement
*IEnumerator* and *IEnumerable* interfaces in your "Doctors"
collection class.

In which case you will not be required to populate an extra ArrayList
but can directly enumerate the "Doctors" using *foreach* construct.


public interface IEnumerable {
IEnumerator GetEnumerator();
}

public interface IEnumerator {
Boolean MoveNext();
Object Current { get; }
void Reset();
}

You can check these links for more info:
http://www.codeguru.com/Csharp/Csharp/cs_collections/article.php/c5505
http://msdn.microsoft.com/library/d...y/en-us/csspec/html/vclrfcsharpspec_9_3_1.asp


Hope it will help.
 
Back
Top