Skip to content

Instantly share code, notes, and snippets.

@johnallers
Created January 25, 2012 05:06
Show Gist options
  • Save johnallers/1674845 to your computer and use it in GitHub Desktop.
Save johnallers/1674845 to your computer and use it in GitHub Desktop.
Demonstration of the C# compiler using duck typing for the foreach keyword.
namespace Samples
{
using System;
using System.Collections.Generic;
public class CustomEnumerableDemoConsole
{
public static void Main(params string[] args)
{
CustomEnumerable enumerable = new CustomEnumerable("One", "Two", "Three");
// "foreach" will work on any type that has a GetEnumerator() method, which returns
// a type that has a Current property getter and a MoveNext() method.
foreach (string item in enumerable)
{
Console.WriteLine(item);
}
}
}
// A custom enumerable which has a GetEnumerator() method, but does NOT implement IEnumerable.
public class CustomEnumerable
{
// A custom enumerator which has a Current property and a MoveNext() method, but does NOT implement IEnumerator.
public class CustomEnumerator
{
private readonly CustomEnumerable _enumerable;
private int _index = -1;
public CustomEnumerator(CustomEnumerable enumerable)
{
_enumerable = enumerable;
}
private IList<string> Items
{
get { return _enumerable._Items; }
}
public string Current
{
get { return _index >= 0 ? Items[_index] : null; }
}
public bool MoveNext()
{
if (_index < Items.Count-1)
{
_index++;
return true;
}
return false;
}
}
private IList<string> _Items;
public CustomEnumerable(params string[] items)
{
_Items = new List<string>(items);
}
public CustomEnumerator GetEnumerator()
{
return new CustomEnumerator(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment