Why is this code (both sets of code taken straight from CA1819: Properties should not return arrays):
public class Book
{
private string[] _Pages;
public Book(string[] pages)
{
_Pages = pages;
}
public string[] Pages
{
get { return _Pages; }
set { _Pages = value; }
}
}
Worse than this code:
public class Book
{
private Collection<string> _Pages;
public Book(string[] pages)
{
_Pages = new Collection<string>(pages);
}
public Collection<string> Pages
{
get { return _Pages; }
}
}
I saw Jon Skeet's answer to a previous question which is similar but not exactly the same. I understand that the ReadOnlyList<T>
wraps the array and returns references to it rather than a full copy.
I also read Eric Lippert's article on why arrays are considered somewhat harmful.
However, both Jon's answer and Eric's answer seem to be based on the fact that you don't want the caller to be able to change the values in the array.
And in this Microsoft article Choosing Between Properties and Methods, they say:
Use a method where the operation returns an array because to preserve the internal array, you would have to return a deep copy of the array, not a reference to the array used by the property.
Which seems to confirm that everyone wants to preserve the internal array.
In the CA1819 article, they demonstrate two problematic usages which are fixed by first using a method and then a ReadOnlyCollection<T>
which is consistent with both Jon and Eric's writings. However, they then go ahead and say that in the case you want the caller to be able to modify the property you should fix the rule violation by using a Collection<T>
.
I want to know why using a Collection<T>
is better than using an array when you don't care about preserving the the internal array (and in fact, want it to be changed)? What am I missing?
In this answer by Jon he says:
if you're happy with callers mutating your data, then an array will work fine...
EDIT: So what is the catch? Why does Microsoft still flag using an array as bad (causes a rule violation) and recommend using a collection to fix it when you want to be able to change the data?