VB.Net: test multiple values for equality?
13,815
Solution 1
If val1 = valN AndAlso val2 = valN AndAlso ... Then
End If
This can get cumbersome when testing more than a few values.
Solution 2
If you have a lot of values to test and do this very often, you could write you a helper like this:
Public Function AllTheSame(ByVal ParamArray values() As Object) As Boolean
For index As Integer = 1 To values.Length - 1
If values(0) <> values(index) Then Return False
Next
Return True
End Function
<Fact()> Public Sub testAllTheSame()
Assert.True(AllTheSame("Test"))
Assert.True(AllTheSame("Test", "Test"))
Assert.True(AllTheSame("Test", "Test", "Test"))
Assert.True(AllTheSame(1234))
Assert.True(AllTheSame(1234, 1234, 1234))
Assert.False(AllTheSame("Test", "Test2"))
Assert.False(AllTheSame("Test", "Test", "Test3"))
Assert.False(AllTheSame(1234, 1234, 987))
End Sub
Solution 3
There is no way to chain them together like that. You need to break it up into pair'd comparisions linked by AndAlso
if val1 = val2 AndAlso val2 = val3 AndAlso val1 = val3 Then
Comments
-
mcjabberz almost 2 years
How do you test multiple values for equality in one line? Basically I want to do
if (val1 == val2 == val3 == ... valN)
but in VB.Net.
-
Patrick McDonald about 15 yearsYou don't need the last comparison: val1 = val3
-
JaredPar about 15 years@Patrick, it's debatable. You can exclude the val1 = val3 if you know the type has transitive equality. While this is true for most types I have found the occasional comparison which flunks this test due to 1) explicit insanity or 2) bugs in equality.
-
Patrick McDonald about 15 years@Jared, fair enough, I wouldn't like to have to write the condition when N starts getting alot bigger then :)
-
JaredPar about 15 years@Patrick, ideally everyone would implement equality in a transitive fashion and we wouldn't have to worry about this at all :)