Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should you avoid to iterate over immutable value-type collections using foreach?

Tags:

c#

.net

In a coding standards document, I found this statement:

Avoid using foreach to iterate over immutable value-type collections. E.g. String arrays.

Why should this be avoided ?

like image 774
driis Avatar asked Feb 16 '10 13:02

driis


2 Answers

You shouldn't avoid it. The coding standard document you're reading is talking nonsense. Try to find the author and ask him to explain.

Aside from anything else, string is a reference type and arrays are always mutable... this makes me concerned about the quality of the rest of the document, to be honest. Are there any other suspicious recommendations?

(It's possible that "immutable" was meant to refer to the value type rather than the collection - the fact that it's ambiguous is another worrying sign, IMO.)

like image 59
Jon Skeet Avatar answered Oct 24 '22 01:10

Jon Skeet


I think that the reason for that statement is that it's written prior to .NET 2.0.

When using foreach in .NET 1.x it was using the IEnumerable interface (as the IEnumerable<T> interface didn't exist yet.) When iterating over a value type collection, the enumerator would box each item to be able to return it as an object reference, then the foreach code had to unbox it.

A string array is of course not an example of an array of value types. An integer array is.

like image 20
Guffa Avatar answered Oct 24 '22 01:10

Guffa