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.

Imports System

Namespace PerformanceLibrary

Public Class Test

    Private nameValues() As String
    
    Public Sub New()
        nameValues = New String(100) {}
        ' Loading string array with sample data.
        Dim i As Integer
        For i = 0 To 99
            nameValues(i) = "Sample"
        Next i
    End Sub 'New
    
    ' Violates rule: PropertiesShouldNotReturnArrays.
    Public ReadOnly Property Names() As String()
        Get
            Return CType(nameValues.Clone(), String())
        End Get
    End Property
    
    Public Shared Sub 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.
        Dim t As New Test()
        
        Dim i As Integer
        For i = 0 To t.Names.Length - 1
            If t.Names(i) = "SomeName" Then
               ' Perform some operation.
            End If
        Next i 
    End Sub 'Main

End Class 'Test

End Namespace

Community Additions

ADD
Show:
© 2014 Microsoft