Back to Devexpress

CRR0017 - Null check follows usage

coderushforroslyn-118132-static-code-analysis-analyzers-library-crr0017-null-check-follows-usage.md

latest1.4 KB
Original Source

CRR0017 - Null check follows usage

  • Feb 28, 2025

This analyzer detects logical expressions in which the null -check is performed after the value -check. Since boolean operators in C# and Visual Basic are short-circuit, the order of operands determines their execution order. Refer to the following code snippet.

csharp
if(str.Length < 2 || str == null) // CRR0017
    DoSomething();
vb
If str.Length < 2 OrElse str Is Nothing Then ' CRR0017
    DoSomething()
End If

In this example, an attempt to get the str.Length value will be made before checking that the str object is null (Nothing in VB). This will cause the System.NullReferenceException exception in case the str object is null (Nothing in VB). To avoid this, swap the operands so that the null -check is performed before any other checks. The execution will break as soon as one of the OR operands returns true.

csharp
if (str == null || str.Length < 2)
    DoSomething();
vb
If str Is Nothing OrElse str.Length < 2 Then
    DoSomething()
End If

See Also

Suppress Analyzers