The title really says it all. In VB.NET is there a difference between these statements when checking for value equality
Dim notEqualsCompare as Boolean = Not a = b
Dim angleBracCompare as Boolean = a <> b
I usually use 'Not a = b' just because it reads better. I read the '<>' operator as 'is less or greater than' which only really makes sense for numeric values, but from my brief testing they behave the same.
Is there ever a situation where one is preferable?
In practice, they should always be functionally equivalent.
As mentioned in one of the other answers, Not a = b is logically two separate operations. You may trust that the compiler will optimize that for you, but, regardless, most programmers would agree that, if a language has an operator to do what you want, you should generally use that feature of the language rather than using multiple operations to accomplish the same result. If you don't like the language, choose another language. But if you're going to use VB, it's best to get used to it and take advantage of it's syntax.
Technically, though, it's worth mentioning that they aren't necessarily the same. All three of the following lines could technically have different results:
result = Not a = b
result = a <> b
result = Not a.Equals(b)
The reason why they can be different is because VB allows you to override the = operator (equality test, not assignment), the <> operator, the Not operator, and the Equals method. So, even though it would be horrendous to override those things and provide differing functionality for each, it is technically possible. For obvious reasons, the "official" guidelines from Microsoft recommend that they always work consistent to each other.
Consider:
Public Sub Main()
Dim a As New Crazy()
Dim b As New Crazy()
Console.WriteLine(a = b) ' False
Console.WriteLine(a.Equals(b)) ' True
Console.WriteLine(a <> b) ' False
Console.WriteLine(Not a) ' "Opposite"
Console.WriteLine(Not a = b) ' True
Console.WriteLine(Not a.Equals(b)) ' False
End Sub
Private Class Crazy
Public Shared Operator <>(x As Crazy, y As Crazy) As Boolean
Return False
End Operator
Public Shared Operator =(x As Crazy, y As Crazy) As Boolean
Return False
End Operator
Public Overrides Function Equals(obj As Object) As Boolean
Return True
End Function
Public Shared Operator Not(value As Crazy) As String
Return "Opposite"
End Operator
End Class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With