views:

1151

answers:

3

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.

+5  A: 
If val1 = valN AndAlso val2 = valN AndAlso ... Then
End If

This can get cumbersome when testing more than a few values.

Jim H.
+1  A: 

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
JaredPar
You don't need the last comparison: val1 = val3
Patrick McDonald
@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.
JaredPar
@Jared, fair enough, I wouldn't like to have to write the condition when N starts getting alot bigger then :)
Patrick McDonald
@Patrick, ideally everyone would implement equality in a transitive fashion and we wouldn't have to worry about this at all :)
JaredPar
+1  A: 

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
dummy