All docs
V20.1
20.1
19.2
19.1
The page you are viewing does not exist in version 19.1. This link will take you to the root page.
18.2
The page you are viewing does not exist in version 18.2. This link will take you to the root page.
18.1
The page you are viewing does not exist in version 18.1. This link will take you to the root page.
17.2
The page you are viewing does not exist in version 17.2. This link will take you to the root page.

CRR2007 - IIF function has identical result arguments

  • 2 minutes to read

This analyzer detects the IIF ternary function in Visual Basic which has two identical arguments:

Dim condition as Boolean;
Dim a, b As Integer

Dim result = IIf(condition, (a + b), (b + a))

In this example, the IIF function returns the same result regardless of the condition. To fix this redundant expression, you can modify this code (for example, change one of the argument in the IIF function).

In some cases, for example, when you need to read data from a database or some file, the IIF function can cause the side effect. For example, the code below produces the following results: value1 = 1, the first "ter.Expr()" value = 1, and the second "ter.Expr()" = 2:

Namespace ConsoleApp

    Public Class Ternary

        Dim count As Integer

        Function Expr() As Integer
            count = count + 1
            Return count
        End Function

    End Class
End Namespace

Module Module1


    Sub Main()

        Dim ter As New Ternary()

        Dim value1 = IIf(True, ter.Expr(), ter.Expr())

    End Sub

End Module

The side effect can appear if you assign the "ter.Expr()" value to some variable and use it in your program. Unlike the If function, the IIF function calculates each result argument when it checks the condition. In the example above, IIF calls both "ter.Expr()" regardless of the return value.

To avoid the side effect, change the ternary expression or use the IF function instead IIF.