Skip to content

Instantly share code, notes, and snippets.

@ploeh

ploeh/Foo.cs

Created Jan 26, 2018
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@ploeh 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
You can’t perform that action at this time.