Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .NET, Array only extends IEnumerable, so will there be boxing and unboxing when a foreach loop goes through a value type array?

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

like image 605
Cui Pengfei 崔鹏飞 Avatar asked Dec 27 '22 22:12

Cui Pengfei 崔鹏飞


1 Answers

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.

like image 73
CodesInChaos Avatar answered Jan 25 '23 22:01

CodesInChaos