Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does foreach apply boxing on IEnumerable<struct>?

I believe the C# compiler will rewrite foreach into a for when it is used on ordinary arrays (such as int[]). However, for collections that store a struct, will boxing result from iterating its contents?

For example, does the code below rely on boxing (IEnumerable<KeyValuePair<int,byte>>) to iterate the contents of dict?

void DoSomething(Dictionary<int,byte> dict) {
    foreach(KeyValuePair<int,byte> itr in dict)
        m_correlation += itr.Key; }
like image 619
Mr. Smith Avatar asked Mar 29 '26 21:03

Mr. Smith


1 Answers

No, the above code does no boxing.

If you'd used IDictionary<int, byte> as the argument (or IEnumerable<KeyValuePair<int, byte>>), the enumerator itself would get boxed, since the dictionary class, like many collections, have a struct enumerator (to save an object allocation every time you call foreach).

In the code above, the compiler would call the dictionary's GetEnumerator method, rather than the (implicitly implemented) IEnumerable<T> method.

like image 120
Eli Arbel Avatar answered Apr 02 '26 21:04

Eli Arbel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!