tags:

views:

129

answers:

3
using System;
using System.Collections;
namespace Iterator_test
{
 class Day
 {
    int days_idx = -1;
    private String[] days = { "mon", "tue", "wed","thu","fri","sat","sun" };
    public IEnumerable getdays()
    {
        days_idx++;
        yield return days[days_idx];
    }
 }
 class Program
 {
    static void Main(string[] args)
    {
        Day d = new Day();
        foreach (string day in d.getdays())
        {
            Console.WriteLine(day);
        }
    }
  }
}

Actually the output should be,

mon
tue
wed
thu
fri
sat 
sun

but its printing only "mon" as,

mon

What will be the reason?

+13  A: 

This is happening because there's no loop in your getdays method. You just yield once, returning the first item - "mon" - and that's it!

Here's an easy fix. (If possible, change the IEnumerable return type to IEnumerable<string> too.)

public IEnumerable getdays()
{
    foreach (string day in days)
    {
        yield return day;
    }
}
LukeH
Thanks you so much Luke..
Babu
+1 - I typically don't vote when I have provided an answer myself, but you get one for good rewrite and improvement suggestions.
Fredrik Mörk
+7  A: 

You need to have a loop around the yield return:

public IEnumerable getdays()
{    
    while (days_idx < 6)
    {
        days_idx++;
        yield return days[days_idx];
    }    
}
Fredrik Mörk
ya its working..Thanks.
Babu
+1  A: 

Luke and Gonzalo are correct.

as an alternate approach as your getdays seems to be readonly and doesn't particularly do much else (from your example)

class Day
{
    public IEnumerable days
    {
        get
        {
            return new string[] { "mon", "tue", "wed", "thu", "fri", "sat", "sun" };
        }
    }

}
class Program
{
    static void Main(string[] args)
    {
        Day d = new Day();
        foreach (string day in d.days)
        {
            Console.WriteLine(day);
        }
    }
}
Kamal
@Kamal: You are a Genius man.Its working.Thank you.
Babu
short answer - tested - works :)yield is more about the retaining state of the method. this explains it nicelyhttp://www.alteridem.net/2007/08/22/the-yield-statement-in-c/
Kamal
@Kamal: The link is nicely explaining yield..
Babu