Array only extends the non-generic version of IEnumerable, so will there be boxing and unboxing when a foreach loop goes through a value type array?
I am guessing not, because that would be lame. If my guess is right, then how does foreach go through a value type array? Does it not use the Array.GetEnumerator method? And if not, why does Array extends IEnumerable?
Thanks
Array
has a lot of special casing in the runtime. In particular it is pseudo-generic. i.e. if you specify a concrete array type like T[]
implement the generic collection interfaces like IEnumerable<T>
.
If I recall correctly it even supported non boxing iteration with foreach
before generics by having GetEnumerator
return a concrete type with a strongly typed Current
. This works since foreach
does not require the IEnumerator
/IEnumerable
interfaces, but works with correctly named members too.
So you can iterate over arrays with foreach
without boxing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With