Export (0) Print
Expand All

Properties should not return arrays

TypeName

PropertiesShouldNotReturnArrays

CheckId

CA1819

Category

Microsoft.Performance

Breaking Change

Breaking

A public or protected property in a public type returns an array.

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.

To fix a violation of this rule, make the property a method.

Do not exclude a warning from this rule.

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.
                }
            } 
        
        }
    }
}

Community Additions

ADD
Show:
© 2014 Microsoft