Why is this an issue?

Properties provide a way to enforce encapsulation by providing property procedures that give controlled access to Private fields. However, in classes with multiple fields, it is not unusual that copy-and-paste is used to quickly create the needed properties, which can result in the wrong field being accessed by the property procedures.

Class C
    Private _x As Integer
    Private _Y As Integer

    Public ReadOnly Property Y As Integer
        Get
            Return _x ' Noncompliant: The returned field should be '_y'
        End Get
    End Property
End Class

This rule raises an issue in any of these cases:

For simple properties, it is better to use auto-implemented properties (VB.NET 10.0 or later).

Field and property names are compared as case-insensitive. All underscore characters are ignored.

How to fix it

Code examples

Noncompliant code example

Public Class Sample

    Private _x As Integer
    Private _y As Integer

    Public Property Y As Integer
        Get
            Return _x   ' Noncompliant: field '_y' is not used in the return value
        End Get
        Set(value As Integer)
            _x = value  ' Noncompliant: field '_y' is not updated
        End Set
    End Property

End Class

Compliant solution

Public Class Sample

    Private _x As Integer
    Private _y As Integer

    Public Property Y As Integer
        Get
            Return _y
        End Get
        Set(value As Integer)
            _y = value
        End Set
    End Property

End Class

Resources