How to write 2 operators that differ only in operator type in VB.NET

I have the following code example where the only difference between the two parts of the If statement is less / greater than the statements.

Is there a better way to write this? Can almost do it with the option to define an Operator variable.

        If myVar = true Then

            Do While (X < Y)
                'call Method A
                'the values of X and Y will change within this loop
            Loop

        Else

            Do While (X > Y)
                'call Method A
                'the values of X and Y will change within this loop
            Loop

        End If

      

thanks

+2


a source to share


4 answers


You can use the ternary conditional operator If

just like VB 2008:

Do While (If(myVar, X < Y, X > Y)))
    'call Method A
Loop

      



However, this will be checked myVar

on every iteration, not just once, which is bad for performance.

+2


a source


Dim from As Integer = CInt(iif(myVar, x, y))
Dim until As Integer = CInt(iif(myVar, y, x))

While from < until
    'call Method A
End While

      



Or, if in 2008 or newer, as Samir says, use the ternary conditional operator to avoid the CInt cast.

+2


a source


You can use a delegate:

Public Function LessThan(Of T As IComparable)(ByVal A As T, ByVal B As T) As Boolean
    Return A.CompareTo(B) < 0
End Function

Public Function GreaterThan(Of T AS IComparable)(ByVal A As T, ByVal B As T)  As Boolean
    Return A.CompareTo(B) > 0
End Function

      


Dim comparer As Func(Of Integer,Integer,Boolean) = AddressOf GreaterThan(Of Integer)
If myVar Then comparer = AddressOf LessThan(Of Integer)

Do While comparer(X,Y)
    ''#call Method A
    ''#the values of X and Y will change within this loop
Loop

      


Of course, this requires VS2008. For fun:

Do While CBool(Y.CompareTo(Y) * -1) = myVar
    ''#...
End While

      

+1


a source


Do While ((myVar And X < Y) Or (Not myVar And X > Y))
    ' call Method A
Loop

      

0


a source







All Articles