Why is this an issue?

Most developers expect property access to be as efficient as field access. However, if a property returns a copy of an array or collection, it will be much slower than a simple field access, contrary to the caller’s likely expectations. Therefore, such properties should be refactored into methods so that callers are not surprised by the unexpectedly poor performance.

This rule tracks calls to the following methods inside properties:

How to fix it

Code examples

Noncompliant code example

Private fFoo As New List(Of String) From {"a", "b", "c"}
Private fBar As String() = {"a", "b", "c"}

Public ReadOnly Property Foo() As IEnumerable(Of String) ' Noncompliant: collection fFoo is copied
    Get
        Return fFoo.ToList()
    End Get
End Property

Public ReadOnly Property Bar() As IEnumerable(Of String) ' Noncompliant: array fBar is copied
    Get
        Return DirectCast(fBar.Clone(), String())
    End Get
End Property

Compliant solution

Private fFoo As New List(Of String) From {"a", "b", "c"}
Private fBar As String() = {"a", "b", "c"}

Public Function GetFoo() As IEnumerable(Of String)
    Return fFoo.ToList()
End Function

Public Function GetBar() As IEnumerable(Of String)
    Return DirectCast(fBar.Clone(), String())
End Function

Resources

Documentation