Why do you want to call moveNext? Just leave out the .Current
:
public class DaysOfTheWeek: IEnumerable
{
private string[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
public IEnumerator GetEnumerator()
{
return days.GetEnumerator();
}
}
Otherwise use a while
loop since:
public class DaysOfTheWeek: IEnumerable
{
private string[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
public IEnumerator GetEnumerator()
{
var enumerator = days.GetEnumerator();
while(enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
}
Explanation: The GetEnumerator()
method always returns a new enumerator, so if you call GetEnumerator().Current
, then the MoveNext()
function has not been called on the newly returned instance! Use a variable as stated in my second example, instead.