C# Enumerator
13 August 2022
What is Enumerator?
Enumerator provides itteration over a list.
Let’s see in a example;
static void Main(string[] args)
{
string[] items = new string[] { "Apple", "Juice", "Beer", "Water" };
var enumerator = items.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
Console.ReadKey();
}
It will itterate until MoveNext()
method will return false
And the result will be,
Just like itteration with foreach,
static void Main(string[] args)
{
string[] items = new string[] { "Apple", "Juice", "Beer", "Water" };
foreach (var item in items)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
What about performances?
Foreach is at least 5 times faster!