As I was reviewing the code yesterday, I noticed some strange behavior. I repeated the set of types A The declaration and use of Enumerable were separated (I declared and defined a variable using some Linq, and then iterated through it later through foreach). However, when I changed the type of the enumeration from IEnumerable<A> to IEnumerable<B> , I left foreach next, where the enumerated was of type IEnumerable<B> .
IEnumerable<B> enumerable = someEnumerableOfB foreach(A a in enumerable)
The following is a far-fetched example of the behavior I found:
IEnumerable<IEnumerable> enumerables = Enumerable.Range(1, 5).Select(x => new List<int> { x }); foreach (StringComparer i in enumerables) //this compiles { //do something here } foreach (int i in enumerables) //this doesn't compile { //do something here } IEnumerable<StringBuilder> stringBuilders = Enumerable.Range(1, 5).Select(x => new StringBuilder(x.ToString())); foreach (FileStream sb in stringBuilders) //this doesn't compile { //do something here }
I was surprised to see the first compile. Can someone explain why this works? I assume this has something to do with IEnumerable having an interface, but I can't explain it.
source share