Created
January 26, 2018 09:40
-
-
Save ploeh/a96c519cb4ec83ab96487b37c84e1e32 to your computer and use it in GitHub Desktop.
Enumerating over generic and non-generic enumerators 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
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class Foo : IEnumerable<int> | |
{ | |
public IEnumerator<int> GetEnumerator() | |
{ | |
yield return 42; | |
yield return 1337; | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
throw new NotImplementedException(); | |
} | |
} |
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
using System; | |
using System.Collections.Generic; | |
using Xunit; | |
public class FooTests | |
{ | |
[Fact] | |
public void ForEachWorks() | |
{ | |
var results = new List<int>(); | |
foreach (var i in new Foo()) | |
results.Add(i); | |
Assert.Equal(new List<int> { 42, 1337 }, results); | |
} | |
[Fact] | |
public void ForEachOnUngenericThrows() | |
{ | |
var results = new List<object>(); | |
Assert.Throws<NotImplementedException>(() => | |
{ | |
foreach (var x in (System.Collections.IEnumerable)(new Foo())) | |
results.Add(x); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Both tests pass: