2 ms·
Interestingly, c#’s foreach construct can operate on types that conform the the IEnumerable/IEnumerator interface even if they don’t implement it; you can have
by jameshart 7y ago
Interestingly, c#’s foreach construct can operate on types that conform the the IEnumerable/IEnumerator interface even if they don’t implement it; you can have a GetEnumerator method return a struct with MoveNext and Current members and it will be stack allocated, so long as the variable on which you foreach is typed with the concrete type rather than IEnumerable.
Language integrated query comprehension is also duck-typed, so if you explicitly implemented Select and Where and friends to all return appropriately crafted structs, you could write full LINQ queries and enumerate them without heap allocations.
But you’re right that to use LINQ to objects you must have an IEnumerable because you rely on the type to bring in the extension methods.
Be interesting to imagine what c# language features would be needed to deliver a stack-allocatable LINQ...