CA1819: Properties shouldn't return arrays - What is the right alternative?

Efrain picture Efrain · Oct 19, 2011 · Viewed 8.6k times · Source

I encountered this FxCop rule before and wasn't really content with how to solve violations (thread1, thread2). I now have another case where I need to correct violations of the CA1819 kind.

Specifically, I have an algorithm-library that performs some analytic calculations on a curve (x,y), with a public "input object" like this:

public class InputObject
{
        public double[] X { get; set; }
        public double[] Y { get; set; }
        // + lots of other things well
}

This object's X and Y properties are used in hundreds of locations within library, typically using indexes. The input object is never altered by the algorithms, but actually it shouldn't matter if so. Also, .Length is called pretty frequently. It's a mathematical library, and double[] is kind of the standard data type in there. In any case, fixing CA1819 will require quite some work.

I thought about using List<double>, since Lists support indexing and are quite similar to arrays but I'm not sure whether this may slow down the algorithms or whether FxCop will be happy with those Lists.

What is the best option to replace these double[] properties?

Answer

Mohamed Abed picture Mohamed Abed · Oct 19, 2011

If it is read only to external consumer and consumer does not want to access it by index then the best is to have a public read only property of type IEnumerable<> with method accessors to add and remove, this way you will not have to expose your array to someone to mess with.

If you need to access the indexers then expose it as read only property of type IList<> and probably return a ReadOnly instance, with methods to add and remove.

This way you keep encapsulation of the internal list and allow consumer to access it in a read only way