|
|
|
|
|
Home
»
C# Language
»
Render iteration through an object collection possible using foreach keyword
|
|
|
|
Author Rank :
|
|
|
Page Views :
|
4180
|
|
Downloads :
|
0
|
|
Rating :
|
Rate it
|
|
Level :
|
Intermediate
|
|
|
Introduction:
Some peoples ask through forums, why when I try to use the foreach keyword to iterate through my customized objects container collection I receive a run time error. Is it compulsory to use the "for" loop with customized container other than an array or an array list? Have I to use only array or array list as containers? But I saw some code in witch "foreach "is used with a customized container as normally without any problem, how I can do so?
As an answer to this question, it is possible to use foreach even a customized objects container is used. In this case there is something that one doesn't have to miss. But first, let me begin to parse the issue step by step through this small example: Imagine that you have to build a software witch handles family members. Say that the two principals' objects used in this context are two classes or types. First the FamilyMember witch represents a single or a stand alone family member and the second element is Family witch plays the role of the family members' container. The FamilyMember class or type is defined as follow:
public class FamilyMember
{
private long _Id;
private string _FirstName;
private string _LastName;
public FamilyMember(long ID, string FirstName, string LastName)
{
this.ID = ID;
this.FirstName = FirstName;
this.LastName = LastName;
}
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
public string LastName
{
get
{
return _LastName;
}
set
{
_LastName = value;
}
}
public long ID
{
get
{
return _Id;
}
set
{
_Id = value;
}
} }
Each family member has an identifier witch is defined as long, a first name witch is a string and a last name witch is also a string. The family witch plays the family members container is defined as so:
public class Family
{
ArrayList FList;
public Family()
{
FList = new ArrayList();
}
public void AddNewMember(long ID, string FirstName, string LastName)
{
FamilyMember x = new FamilyMember(ID, FirstName, LastName);
FList.Add(x);
}
}
When I try this code to iterate through the family members collection:
static void Main(string[] args)
{
Family myFamily = new Family();
myFamily.AddNewMember(1, "Mahmoud", "Bejaoui");
myFamily.AddNewMember(2, "Rafika", "Ben Moussa");
myFamily.AddNewMember(3, "Bechir", "Bejaoui");
myFamily.AddNewMember(4, "Salima", "Bejaoui");
myFamily.AddNewMember(5, "Radhia", "Bejaoui");
string oString = "";
foreach (FamilyMember f in myFamily)
{
oString = oString + f.FirstName + " " + f.LastName + Environment.NewLine;
}
Console.WriteLine(oString);
Console.Read(); }
I receive this run time error:

Figure 1
Now the question is what does it mean GetEnumerator? And how one can configure and use it to prevent this run time error?
Well, as an answer to those two questions, the GetEnumerator is a member of the IEnumerable interface witch is a System.Collection built in member and as seen bellow, this interface is composed by a method that returns an IEnumerator object, this method is called GetEnumerator. This last one supports actions that render possible the iteration through an internal member's collection when it is already implemented by a given class.
interface IEnumerable
{
IEnumerator GetEnumerator();
}
The IEnumerator interface is also useful independently. This is the IEnumerator presentation
interface IEnumerator
{
bool MoveNext();
object Current{ get;}
void Reset(); }
In order to render possible the iteration through the container collection, you have to implement the IEnumerable interface. The fact is that Family class uses indirectly an IEnumerator object behind the scene as the IEnumerable member GetEnumerator returns an IEnumerator object; in this case you have to write code within the GetEnumerator member core so that iteration through internal collection objects will be possible. In this case we will use the "FList" GetEnumerator member as it is already implemented. You can also implement GetEnumerator by your self to suite certain needs. Finally, Family class should be designed as follow:
public class Family : IEnumerable
{
ArrayList FList; public Family()
{
FList = new ArrayList();
}
public void AddNewMember(long ID, string FirstName,string LastName)
{
FamilyMember x = new FamilyMember(ID, FirstName, LastName);
FList.Add(x);
}
#region IEnumerable Members IEnumerator IEnumerable.GetEnumerator()
{
return this.FList.GetEnumerator();
}
#endregion
}
Now try to run the program and you will never receive this kind of error again.

Figure 2
|
|
Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post
Here.
|
|
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
|
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
|
|
|
|
|
|
|
|
|
|
|
|
|