Created
January 25, 2012 05:06
-
-
Save johnallers/1674845 to your computer and use it in GitHub Desktop.
Demonstration of the C# compiler using duck typing for the foreach keyword.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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