I'm currently learing C# for the purpose of effectivly usingRazor and Umbraco, I have a little bit of background in PHP and a reasonable knowledge in JavaScript.
I came across the IEnumerator interface and have had difficulty getting my head around it. I've setup a code snippet below to demonstrate looping through an array with foreach:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace cardEnum
{
class suitsEnumerator
{
private static string[] suits = { "Hearts", "Spades", "Diamonds", "Clubs" };
public void showAll()
{
foreach(string x in suits){
System.Console.WriteLine(x);
}
}
}
class run
{
static void Main()
{
Console.WriteLine("The suits are:");
var suits = new suitsEnumerator();
suits.showAll();
Console.ReadKey();
}
}
}
Can someone explain why I would even need to use IEnumerator when I can quite easily loop through the array otherwise. I KNOW this is such a simple question, I just cant think of an reason to use IEnumerable.
Any help at all would be greatly appreciated, thanks!
This is how the enumerator pattern could be implemented in your example. I hope this clarifies a few things, in particular, the relationship between IEnumerable and IEnumerator:
namespace cardEnum {
// simple manual enumerator
class SuitsEnumerator : IEnumerator {
private int pos = -1;
private static string[] suits = { "Hearts", "Spades", "Diamonds", "Clubs" };
public object Current {
get { return suits[pos]; }
}
public bool MoveNext() {
pos++;
return (pos < suits.Length);
}
public void Reset() {
pos = -1;
}
}
class Suits : IEnumerable {
public IEnumerator GetEnumerator() {
return new SuitsEnumerator();
}
}
class run {
static void Main() {
Console.WriteLine("The suits are:");
var suits = new Suits();
foreach (var suit in suits) {
Console.WriteLine(suit);
}
Console.ReadKey();
}
}
}
Of course, this is a contrived example to aid understanding. Since string[] already implements IEnumerable, there's no reason to reinvent the wheel.
Since C# supports the yields keyword, creating an Enumerator got a little easier recently:
namespace cardEnum {
// no explicit SuitsEnumerator required
class Suits : IEnumerable {
public IEnumerator GetEnumerator() {
yield return "Hearts";
yield return "Spades";
yield return "Diamonds";
yield return "Clubs";
}
}
class run {
static void Main() {
Console.WriteLine("The suits are:");
var suits = new Suits();
foreach (var suit in suits) {
Console.WriteLine(suit);
}
Console.ReadKey();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With