Skip to content

Instantly share code, notes, and snippets.

@ploeh
Created January 26, 2018 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ploeh/a96c519cb4ec83ab96487b37c84e1e32 to your computer and use it in GitHub Desktop.
Save ploeh/a96c519cb4ec83ab96487b37c84e1e32 to your computer and use it in GitHub Desktop.
Enumerating over generic and non-generic enumerators in C#
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();
}
}
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);
});
}
}
@ploeh
Copy link
Author

ploeh commented Jan 26, 2018

Both tests pass:

2 passed, 0 failed, 0 skipped, took 0,63 seconds (xUnit.net 2.3.1 build 3858).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment