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; }
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.
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