Reader Level:
Articles

How to use IEnumerable in C#

By mahmoud mahmoud on July 09, 2010
How to use IEnumerable in C#.
  • 0
  • 0
  • 60988


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'>
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

COMMENT USING

Trending up