Render iteration through an object collection possible using foreach keyword

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:

1.gif

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.

2.gif

Figure 2


Recommended Free Ebook
Similar Articles