4 ms·
Structs can implement IEnumerator<T> as you mentioned, but they need to be boxed before any interface methods they implement can be called. So, foreach in C# d
by profquail 14y ago
Structs can implement IEnumerator<T> as you mentioned, but they need to be boxed before any interface methods they implement can be called.
So, foreach in C# does always create at least a tiny bit of garbage -- but in the case above it's likely to be reclaimed very quickly.
- noblethrasher 14y agoNormally value types do need to be boxed before calling interface methods, but C#'s `foreach` statement is special in that the collection expression just needs to conform to the "collection pattern" rather than implement a particular interface (i.e. IEnumerable). An expression conforms to the collection pattern if it has a public `GetEnumerator` method that returns a type that has a public method of type `MoveNext -> bool` and a public method of type `Current -> Type_Of_The_Element`. In other words, `foreach` uses structural typing rather than nominal typing. Incidentally, value types need only generate garbage in a `foreach` statement if they create a disposable `Enumerator`.
- profquail 14y agoInteresting -- I'd read about this once before but forgotten all about it. Good catch!