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 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 to share