Regarding the CA1819 msdn performance warning rule:
Arrays returned by properties are not write-protected, even if the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. Specifically, they might use the property as an indexed property.
I want to know if other objects are mutable when returned by the property, or if this only happens for arrays? If it is only valid for arrays, why?
Let say you have:
int[] ints = new int[] { 1, 2, 3, 4 }
public int[] Ints { get { return ints; } }
The consumer of your class can do:
instance.Ints[0] = 10;
So you're allowing modification of the data of the class.
To prevent this you can done something like this:
public IEnumerable<int> Ints { get { return ints; } }
So the consumer of your class can only read the values but not modify.
Now, why?
Well it depends on the design of your class if you want let modify the data of array, the warning warns you about the fact that maybe you expect that the values of the array cannot be manipulated because you don't have a set
in the property.
PS: there a lot of methods, like readonly collection etc..., to prevent altering your collections
Take a look at this
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