5

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?

1

1 Answer 1

3

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

8
  • Thanks for the answer. I have tried this using object (string) and it does not allow me to modify the value of the string , i want to know if any other object is mutable like arrays(does this happen with any other object type)? Thanks again.
    – Kriss
    Commented Sep 9, 2013 at 14:02
  • Thanks for the answer. I want to know if this happens with other objects type too, (i tried doing this with strings and it doesn't allow modification), are there any other object that are mutable, except arrays? Thanks again.
    – Kriss
    Commented Sep 9, 2013 at 14:08
  • The object itself is not mutable, you can change it's data, the problem arises with collection in generals, like List<T> etc. Commented Sep 9, 2013 at 14:10
  • Can we say that the only mutable objects in this situation are arrays and this does not happen with other types of objects like List<T> etc. For example i have private IDbCommand idbCommand; and property: public IDbCommand Command { get { return idbCommand; } } is idbCommand mutable??? Thanks a lot.
    – Kriss
    Commented Sep 9, 2013 at 14:32
  • Can you tell me why this only happens with arrays?
    – Kriss
    Commented Sep 9, 2013 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.