3 ms·
Normally 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
by noblethrasher 14y ago
Normally 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!