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