Suspicious Predeclared Instance Access

This inspection warns about references to the default instance of a class, inside that class.

Reasoning

While a stateful default instance might be intentional, when it isn't it's easily a source of bugs. Use the Me qualifier to explicitly refer to the current instance and eliminate any ambiguity. Global state accidentally stored in a class' default instance is not shared by all other instances of that class.

Default severity

Warning

Inspection type

CodeQualityIssues

Examples

This example should trigger a result

Module1 (StandardModule)
Option Explicit Public Sub Test1() UserForm1.Show ' the default instance is being shown End Sub Public Sub Test2() With New UserForm1 .Show ' a new instance is being shown End With End Sub
UserForm1 (UserFormModule)
Option Explicit Private ClickCount As Long Private Sub CommandButton1_Click() ClickCount = ClickCount + 1 UserForm1.TextBox1.Text = ClickCount ' only TextBox1 on the default instance is affected End Sub

This example should NOT trigger a result

Module1 (StandardModule)
Option Explicit Public Sub Test1() UserForm1.Show ' the default instance is being shown End Sub Public Sub Test2() With New UserForm1 .Show ' a new instance is being shown End With End Sub
UserForm1 (UserFormModule)
Option Explicit Private ClickCount As Long Private Sub CommandButton1_Click() ClickCount = ClickCount + 1 Me.TextBox1.Text = ClickCount ' always works as expected End Sub

Rubberduck.CodeAnalysis.Inspections.Concrete.SuspiciousPredeclaredInstanceAccessInspection.cs (Prerelease-v2.5.9.6289)