C# IEnumerable vs IEnumerator

When we work with Collections in C# we need to iterate the items of collections. One way fo doing is this foreach loop.

 

The class should implenet IEnumerable interface. The IEnumerable interface also inehirts from IEnumerator interface/

 

 

 

codes:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IEnumerableandIEnumerator
{
    class Player
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Player(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

    class Team:IEnumerable
    {
       private Player[] playerArray=new Player[4]; //aggregated class

        public Team()
        {
            playerArray[0] = new Player("Virat", 28);
            playerArray[1] = new Player("Dhoni", 35);
            playerArray[2] = new Player("Rohit", 29);
            playerArray[3]= new Player("Yuvraj",34);
        }

        public IEnumerator GetEnumerator()
        {
            return playerArray.GetEnumerator();
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            
            //string[] PlayerArray = {"Virat", "Rohit", "Dhoni"};
            //foreach (var items in PlayerArray)
            //{
            //    Console.WriteLine("Player is {0}",items);
            //}
            Team obj=new Team();

            foreach (Player iteemPlayer in obj)
            {
                Console.WriteLine("Name is {0} and Age is {1}",iteemPlayer.Name,iteemPlayer.Age);
            }
            Console.ReadLine();
        }
    }
}

 

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.