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 ?
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 ?
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.)
I agree with Jon that the advice makes little sense. My guess is that the author discovered that you cannot change the value of the current item when iterating. However, if you're iterating a collection of reference types you can still modify the object the current item points to. Perhaps (s)he concluded that iteration was somehow broken for value type collections.
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.