|
|
|
|
|
Home
»
C# Language
»
Render iteration through an object collection possible using foreach keyword
|
|
|
Author Rank:
|
|
Total page views :
2463
|
|
Total downloads :
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
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
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
Bechir Bejaoui
The author holds a master degree in NTIC specialized in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by the economic sciences and management university of Tunis "FSEGT". He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.
|
|
|
|
|
|
|
|
|
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.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
|
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.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|