Question

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; }
Was it helpful?

Solution

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.

OTHER TIPS

No it won't.

Nothing from the above can be boxed. Your Dictionary is already a reference type.. and a KeyValuePair is a struct. The compiler generated call to GetEnumerator() will return a generic Enumerator struct.. but that is called on dict.. which is already a reference type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top