Skip to content

Instantly share code, notes, and snippets.

@gprasant
Created October 22, 2011 04:13
Show Gist options
  • Save gprasant/1305610 to your computer and use it in GitHub Desktop.
Save gprasant/1305610 to your computer and use it in GitHub Desktop.
shows how the foreach does not necessarily require an IEnumerable. Demonstrates the use of Duck typing in C#
// resembles a IEnumerator. has Current and MoveNext
public class Duckerator
{
public bool MoveNext()
{
return false;
}
public Object Current { get; private set; }
}
//represents an IEnumerable. has a GetEnumerator method
public class Duckable
{
public Duck GetEnumerator()
{
return new Duckerator();
}
}
public void TestADuck()
{
var duckable = new Duckable();
foreach(var duckItem in duckable)
{
//no compile errors...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment