Sponsored Ad

Thursday, May 27, 2010

Working with Collections | Collection Loop Through Example using foreach

Working with Collections

 

Collections are new to some programmers. So we desided to write a post on this. Collections are ingherited from IEnumerator interface.

In this example Class3 contains the three methods of Class3 interface and in this class these 3 methods implemented.

MoveNext()

Reset()

And a property Current

So using forearch now you can loop through the all collection objects. Also you need to explicitly check for iteration count in MoveNext()

Method. Because it does not take care internally.

 

Working with Collections | Collection Loop Through Example using foreach

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Console_App
{
    public class Class1
    {
        public static void Main()
        {
            Class2 obj = new Class2();
            foreach (string str in obj)
            {
                Console.WriteLine(str);
                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
    class Class2
    {
        public IEnumerator GetEnumerator()
        {
            return new Class3();
        }
    }
    class Class3 : IEnumerator
    {
        public string[] a1 = new string[3] { "String 1", "String 2", "String 3" };
        public int i = -1;
        public bool MoveNext()
        {
            i++;
            Console.WriteLine("MoveToNext Value: " + i);
            if (i == 3)
                return false;
            else
                return true;
        }
        public void Reset()
        {
            Console.WriteLine("Reset");
        }
        public object Current
        {
            get
            {
                Console.WriteLine("Current Value : " + a1[i]);
                return a1[i];
            }
        }
    }
}

No comments:

Post a Comment

Sponsored Ad

Development Updates