Monday, April 7, 2008

Loops and iterators in c# (5 ways).

It is suggested to inspect several ways to implement loop in c#.

For example, we need display all days: Sunday .. Saturday with help of loop (or iterators).

Operator For:

static void sample_For_Days()
{
for (int index = 0; index < DaysNames.DAYS.Length; index++)
{
string day = DaysNames.DAYS[index];
Console.Write(day + " ");
}
Console.WriteLine();
}




Operator foreach:



foreach (string day in DaysNames.DAYS)
{
Console.Write(day + " ");
}
Console.WriteLine();





Method Array.Foreach:



Array.ForEach(DaysNames.DAYS, 
delegate(string day) { Console.Write(day + " "); });
Console.WriteLine();


Operator ForEach with help of interfaces IEnumerable and IEnumerator


class implementation



public class DaysOfTheWeek_IEnumerator : IEnumerable, IEnumerator
{
int index;
public DaysOfTheWeek_IEnumerator()
{
Reset();
}
#region IEnumerable
public IEnumerator GetEnumerator()
{
return this;
}
#endregion

#region
IEnumerator
public bool MoveNext()
{
return (++index < 7);
}
public void Reset()
{
index = -1;
}
public object Current
{
get { return DaysNames.DAYS[index]; }
}
#endregion
}





usage of foreach



DaysOfTheWeek_IEnumerator week = new DaysOfTheWeek_IEnumerator();

foreach (string day in week)
{
Console.Write(day + " ");
}
Console.WriteLine();





Operator ForEach with help of interfaces IEnumerable and statement yield:



class implementation:



public class DaysOfTheWeek_yield : IEnumerable
{
#region IEnumerable
public IEnumerator GetEnumerator()
{
for (int i = 0; i < DaysNames.DAYS.Length; i++)
{
yield return DaysNames.DAYS[i];
}
}
#endregion
}





usage of foreach:



DaysOfTheWeek_IEnumerator week = new DaysOfTheWeek_IEnumerator();

foreach (string day in week)
{
Console.Write(day + " ");
}
Console.WriteLine();





Console output shows, all methods display same results:



greenshot_2008-04-07_10-41-49



Reference:



foreach, in (C# Reference)



Iterators (C# Programming Guide)



yeild (C# Reference)

No comments: