Created
October 22, 2011 04:13
-
-
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#
This file contains hidden or 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
// 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