Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA1819: Properties should not return arrays. Does this rule apply for other objects too?

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?

like image 240
Kriss Avatar asked Oct 22 '22 01:10

Kriss


1 Answers

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

like image 157
Alessandro D'Andria Avatar answered Nov 10 '22 00:11

Alessandro D'Andria