Jump to content

Collection

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
one198

one198

    Newbie

  • Members
  • Pip
  • 1 posts
Hello Guys

I Am new to this forum as well as C# programming Language .Nowadays I am studying Collection C# and used some web site and E book to learn C#.Below Coding I got from a one of web site but I could not understand what is happen in that coding.




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

public class Fruit
 {
  //this is a bad way to declare fields in a class
  //but this is just an example 
  public string name;
  public bool ripe;
  public int num;

  public Fruit(string nme, bool rp, int n)
  {
   name = nme;
   ripe = rp;
   num = n;
  }
 }


public class Fruits :IEnumerable,IEnumerator
{
 Fruit[] fruitArray;
 //current position in array set to initial position
 int position = -1;
 //Create a basket of fruit    
 public Fruits()
 {
  fruitArray = new Fruit[3];
  fruitArray[0] = new Fruit("Banana",false,3);
  fruitArray[1] = new Fruit("Apples",true,5);
  fruitArray[2] = new Fruit("Oranges",true,3);
 }

 //Implement IEnumerable

 public IEnumerator GetEnumerator()
 {
 return (IEnumerator)this;
 }

 //Implement IEnumerator
 public bool MoveNext()
 {
  position++;
  if (position < fruitArray.Length)
  {
   return true;
  }
  else
  {
   return false;
  }
 }
 public void Reset()
 {
  position = -1;
 }
 public object Current
 {
  get{return fruitArray[position];}
 }
}

class FruitBar
{
 static void Main(string[] args)
 {
  Fruits fruitbasket = new Fruits();
  //Present only the ripe fruit
  foreach (Fruit f in fruitbasket)
  {           
   if (f.ripe == true)
   Console.WriteLine("Name : {0}",f.name);
   Console.WriteLine("Amount : {0}",f.num);  
  }     
  string x = Console.ReadLine();
  }
 }




So anyone can tell me ,which part we used IEnumerator?Purpose Of the IEnumerator?

Thank Youd

#2
gokuajmes

gokuajmes

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 518 posts
Inumerator derives from the Interface ,based . It checks if the Coolection ,ListItem ..etc is enumerable that is are they able to count the number of items ,so that it may be looped using a For or a Foreach statement.KickBack to the MSdn Library for more information.