C# – CA1819: Properties should not return arrays. Does this happen only with arrays? If yes, why

arrayc

I have a question about CA1819 msdn performance warning.

The rule is: 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 understand the rule.

I want to know if this happens only with arrays? If yes, why?

Best Answer

Arrays are reference types. That is when a property returns an array object it's returning a pointer/reference to it's internal array. The caller of the property can now modify that internal array (as they have a pointer to it), this is generally unwanted. To stop this you can return a copy of the internal array but now your doing a memory allocation and copy every time the property is used, and given that properties are meant to be light-weight that's not good.

This happens with any reference type that is mutable. If you have a private reference to a mutable reference type (Like a Stream, List or Dictionary) and you return that reference in a property than the caller can modify your data. If you have a value type (structs in C#) than they are always copied when they're returned from the property so the caller can't then modify your internal version of the data.