Search
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Sat, 01-Nov-2014 Authors
All Time Authors
Sourav.Kayal
39750
Sheonarayan
38050
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

Define your own Collection class that support Iterator Pattern

Hmanjarawala
Posted by under C# category on for Advance level | Points: 250 | Views : 4013 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 4.67 out of 5
3 vote(s)
In this article we are discussing over how to define Iterator classes for our own define class

 Download source code for Define your own Collection class that support Iterator Pattern


Introduction

In my previous article: How to use IEnumerable/IEnumerator interface- I discussed how to use these interfaces with collection classes. Today we will demonstrate how these interfaces works. For that we ‘ll develop our own classes that implement these interfaces.


Objective

Define Enumerable and Enumerator object for User Define data type (i.e. Class)



Using the code

First of all let’s define a class for which we are going to developed Iterator classes. Here is a class for same.

   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 Employee class. This class has three properties – FirstName, LastName and Age –and override method ToString which returns string representation of class.

Now, we’ll define Enumerable class for Employee called EmployeeCollection which implements System.Collection.IEnumerable interface. This class contains Array of Employee class as its data member. This member initializes in constructor as show below
 public EmployeeEnumerable(Employee[] listEmployee)

 {

     employess = new Employee[listEmployee.Length];

     Array.Copy(listEmployee, employess, listEmployee.Length);

 }


In this example we are implementing IEnumerable interface explicitly, reason of doing this is while using GetEnumerator method, I want user only get my version of GetEnumerator method. Let 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);

        }

So, this way we can hide IEnumerable’s method implementation with our own version.

Till now we had developed Enumerable class for our own Class. Now we are going to define Enumerator class for our entity. Below we’ve code for 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 also we are implementing methods of IEnumerator interface explicitly. Hope this class is self describable hence need not to write much specification. So new we are moving how to use this concept. Here is code that uses this 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 define Array of our own Employee class, you can define List<> as well. As we know these both are of System.Collection type of object, so they internally support Enumerable methods. We instantiate our own EmployeeCollection class and then from there we’ll get our Enumerator object for Employee class using GetEnumerator() method and from that object we can iterate over our array members.

Hope you liked this type of concept of iterator pattern.

Page copy protected against web site content infringement by Copyscape
About the Author

Hmanjarawala

Full Name: Himanshu Manjarawala
Member Level: Bronze
Member Status: Member
Member Since: 7/30/2011 7:42:18 AM
Country: India
Himanshu Manjarawala Sr. Software Engineer@AutomationAnywhere http://fieredotnet.wordpress.com/
http://himanshumbri.blogspot.com

I am Himanshu Manjarawala, Graduate in Computer Science and MCA From Veer Narmad South Gujarat University, Surat Gujarat India. Currently working as Sr. Software Developer in Automation Anywhere.
Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)