What is the concrete type for this IEnumerable<string>
?
private IEnumerable<string> GetIEnumerable()
{
yield return "a";
yield return "a";
yield return "a";
}
What is the concrete type for this IEnumerable<string>
?
private IEnumerable<string> GetIEnumerable()
{
yield return "a";
yield return "a";
yield return "a";
}
The concrete implementation of
IEnumerable<string>
returned by the method is an anonymous type generated by the compilerPrints :
The compiler will automatically generate a class that implements both
IEnumerable<T>
andIEnumerator<T>
(in the same class).Jon Skeet has a detailed explanation.
It's a compiler-generated type. The compiler generates an
IEnumerator<string>
implementation that returns three "a" values and anIEnumerable<string>
skeleton class that provides one of these in itsGetEnumerator
method.The generated code looks something like this*:
Or maybe, as SLaks says in his answer, the two implementations end up in the same class. I wrote this based on my choppy memory of generated code I'd looked at before; really, one class would suffice, as there's no reason the above functionality requires two.
In fact, come to think of it, the two implementations really should fall within a single class, as I just remembered the functions that use
yield
statements must have a return type of eitherIEnumerable<T>
orIEnumerator<T>
.Anyway, I'll let you perform the code corrections to what I posted mentally.
*This is purely for illustration purposes; I make no claim as to its real accuracy. It's only to demonstrate in a general way how the compiler does what it does, based on the evidence I've seen in my own investigations.