Skip to content

Instantly share code, notes, and snippets.

@AndrewBarfield
Created April 30, 2012 09:23
Show Gist options
  • Save AndrewBarfield/2556793 to your computer and use it in GitHub Desktop.
Save AndrewBarfield/2556793 to your computer and use it in GitHub Desktop.
C#: System.Collections.IEnumerable: Custom Iterator Example
using System;
namespace IteratorsExample {
class Program {
static void Main(string[] args) {
// Create an instance of the collection class
EvenIntegers ei = new EvenIntegers();
// Iterate with foreach
foreach ( int num in ei ) {
System.Console.Write( num + " " );
}
// Allow user to read output
Console.Read();
}
}
public class EvenIntegers : System.Collections.IEnumerable {
public System.Collections.IEnumerator GetEnumerator() {
for ( int i = 0 ; i < 11 ; i=i+2 ) {
yield return i;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment