Back to Devexpress

CRR0006 - Suspect variable reference in null-check following as-cast

coderushforroslyn-118099-static-code-analysis-analyzers-library-crr0006-suspect-variable-reference-in-null-check-following-as-cast.md

latest1.3 KB
Original Source

CRR0006 - Suspect variable reference in null-check following as-cast

  • Feb 28, 2025

This analyzer detects the following situation.

  1. The variable is assigned with a type-casted value of another variable.
  2. The original variable is checked for null ( Nothing in VB).

The example is shown below.

csharp
public void Test(object obj){
    var str = obj as string;
    if (obj == null) return; // CRR0006
    //...
}
vb
Sub Test(obj As Object)
    Dim str = TryCast(obj, String)
    If obj Is Nothing Then ' CRR0006
        Return
    End If
    '...
End Sub

In this case, the null-check is performed against the wrong variable, because such code is unable to detect the situation when the null value appeared as a result of type-casting a non-null object. You need to change the code as follows.

csharp
public void Test(object obj){
    var str = obj as string;
    if (str == null) return;
    //...
}
vb
Sub Test(obj As Object)
    Dim str = TryCast(obj, String)
    If str Is Nothing Then
        Return
    End If
    '...
End Sub

See Also

Suppress Analyzers