Properties should not return arrays
.NET Framework 2.0
| TypeName | PropertiesShouldNotReturnArrays |
| CheckId | CA1819 |
| Category | Microsoft.Performance |
| Breaking Change | Breaking |
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 negative performance implications of calling such a property. Specifically, they might use the property as an indexed property.
The following example shows a property that violates this rule. The Main method illustrates how a user might write poorly performing code using such a property.
using System; namespace PerformanceLibrary { public class Test { string [] nameValues; public Test() { nameValues = new string[100]; // Loading string array with sample data. for (int i = 0; i< 100; i++) { nameValues[i] = "Sample"; } } // Violates rule: PropertiesShouldNotReturnArrays. public string [] Names { get { return (string[]) nameValues.Clone(); } } public static void Main() { // Using the property in the following manner // results in 201 copies of the array. // One copy is made each time the loop executes, // and one copy is made each time the condition is tested. Test t = new Test(); for (int i = 0; i < t.Names.Length ; i++) { if (t.Names[i] == ("SomeName")) { // Perform some operation. } } } } }