Click here to Skip to main content
Click here to Skip to main content

Tagged as

Define your own collection class that supports the Iterator pattern

, 2 Apr 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
In this article we are discussing how to define Iterator classes for our own classes.

Introduction

In my previous article How to use the IEnumerable/IEnumerator interface, I discussed how to use these interfaces with collection classes. Today we will see how these interfaces work. For that we will develop our own classes that implement these interfaces.

Objective

Define the Enumerable and Enumerator object for the user defines data type (i.e., class).

Using the code

First of all, let’s define a class for which we are going to develop the Iterator classes. Here is the class:

class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return string.Join(" | ", FirstName, LastName, Age);
    }
}

As you can see, here we define the Employee class. This class has three properties – FirstName, LastName, and Age and an override method ToString which returns a string representation of the class. Now we’ll define the Enumerable class for Employee called EmployeeCollection which implements the System.Collection.IEnumerable interface. This class contains an Array of the Employee class as its data member. This member is initialized in the constructor as shown below:

public EmployeeCollection(Employee[] listEmployee)
{
    employess = new Employee[listEmployee.Length];
    Array.Copy(listEmployee, employess, listEmployee.Length);
}

In this example, we are implementing the IEnumerable interface explicitly. The reason for doing this is while using the GetEnumerator method, I want the user to only get my version of the GetEnumerator method. Let us see how to do this:

// This method implemented explicitly, that's why it's
// not visible to user. So user will always use second 
// version of this method.
IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator() as IEnumerator;
}

// User can use this version only
public EmployeeEnumerator GetEnumerator()
{
    return new EmployeeEnumerator(employess);
}

This way we can hide IEnumerable’s method implementation with our own version. Till now we had developed an Enumerable class for our own class. Now we are going to define the Enumerator class for our entity. Below we’ve the code for the Enumerator class.

class EmployeeEnumerator : IEnumerator
{
    Employee[] employess;
    int position = -1;

    public EmployeeEnumerator(Employee[] lstEmployee)
    {
        employess = lstEmployee;
    }

    public Employee Current
    {
        get
        {
            try
            {
                return employess[position];
            }
            catch (IndexOutOfRangeException) { throw new InvalidCastException(); }
        }
    }

    object IEnumerator.Current
    {
        get { return Current; }
    }

    public bool MoveNext()
    {
        position++;
        return position < employess.Length;
    }

    public void Reset()
    {
        position = -1;
    }
}

You can see here that  we are implementing methods of the IEnumerator interface explicitly. I think this class is self describable. Now we are moving into how to use this concept. Here is some code that uses these classes.

static class Enumerator
{
    [STAThread]
    static void Main(string[] args)
    {
        Employee[] list = new Employee[]{
            new Employee() { FirstName="Himanshu", LastName="Manjarawala", Age=30},
            new Employee(){ FirstName="Hetal", LastName="Sangani", Age=26},
            new Employee(){ FirstName="Viral", LastName="Sangani", Age=32},
            new Employee(){ FirstName="Rajesh", LastName="Patel", Age=29},
            new Employee(){ FirstName="Nehal", LastName="Thakkar", Age=30}
        };

        var enumerable = new EmployeeCollection(list);
        var enumerator = enumerable.GetEnumerator();

        while (enumerator.MoveNext())
        {
            Employee e = enumerator.Current;
            Console.WriteLine(e.ToString());
        }
    }
}

Here, we’ve defined an Array of our own Employee class. You can define a List<> as well. As we know, both are of the System.Collection type, so they internally support Enumerable methods. We instantiate our own EmployeeCollection class and then from there we’ll get our Enumerator object for the Employee class using the GetEnumerator() method and from that object we can iterate over our array members. Hope you like this concept of the Iterator pattern.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Himanshu Manjarawala
Team Leader Automation Anywhere Inc.
India India
I am Himanshu Manjarawala, Garduate in Computer Science and MCA From Veer Narmad South Gujarat University, Surat Gijarat India. Currently working as Sr. Software Developer in Automation Anywhere Softwares Pvt. Ltd. Vadodara, Gujarat
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionWhy not inherit from List&lt;T&gt;? PinmemberBernhard Hiller2-Apr-12 22:35 
AnswerRe: Why not inherit from List<T>? PinmemberAndreas Gieriet2-Apr-12 23:32 
QuestionOver-Engineered? [modified] PinmemberAndreas Gieriet2-Apr-12 13:10 
AnswerRe: Over-Engineered? PinmemberMember 30219972-Apr-12 18:33 
Hi Andreas,

thanks for you detail comment or say suggestion.

with this trick, i just want to demonstrate "How to design classes using Iterator pattern" I know there are couple of ways which are simple and will give same behavior.
Himanshu Manjarawala.
Sr. Software engineer @AutomationAnywhere
http://www.himanshumbi.blogspot.com
http://www.fieredotnet.wordpress.com

GeneralRe: Over-Engineered? [modified] PinmemberAndreas Gieriet2-Apr-12 21:38 
GeneralRe: Over-Engineered? PinmemberAndreas Gieriet4-Apr-12 0:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141216.1 | Last Updated 2 Apr 2012
Article Copyright 2012 by Himanshu Manjarawala
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid