ARTICLE

How to use IEnumerable in C#

Posted by mahmoud mahmoud Articles | How do I July 09, 2010
How to use IEnumerable in C#.
Reader Level:


This code snippet shows how to implement IEnumerable in C#.


using System;
using System.Collections;
namespace ConsoleApplication5
{

    class data
    {
        string name;
        int age;
        public data()
        {
        }
        public data(string name, int age)
        {
            this.name = name;
            this.age = age;
        }
        public string _name
        {
            get
            {
                return name;
            }
        }
        public int _age
        {
            get
            {
                return age;
            }
        }
    }
    class people : IEnumerator, IEnumerable
    {
        public IEnumerator GetEnumerator()
        {
            return x.GetEnumerator();
        }

        internal int pos = 0;
        data[] x = new data[4];
        public people()
        {
            x[0] = new data("Ali", 32);
            x[1] = new data("mohammed", 22);
            x[2] = new data("wael", 24);
            x[3] = new data("slah", 34);
        }
        public object Current
        {
            get
            {
                return x[pos];
            }
        }
        public bool MoveNext()
        {
            if (pos <= x.Length)
            {
                ++pos;
                return true;
            }
            else
                return false;
        }
        public void Reset()
        {
            Console.WriteLine("Reset...");
            pos = 0;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            people p = new people();
            foreach (data d in p)
            {
                Console.WriteLine(d._name + " " + d._age.ToString());
            }
        }
    }
}
 

erver'>
Login to add your contents and source code to this article
Article Extensions
Contents added by jayan suthan on Mar 27, 2012

public IEnumerator GetEnumerator(); will return the all methods needed for the interface. so why again we implementing the functions seperately

post comment
     

Please try to at least explain the code.

Posted by Anurag Sarkar Apr 06, 2013
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter