Saturday, February 11, 2006

Non transitive equality in VB.Net

One of the good bits of advice that floats around is to avoid overriding Equals() unless you know what you're doing[1]. The requirements for equality (reflexive, symmetric and transitive) are easily broken if you're not concentrating.

It's a pity no-one told the VB team[2]...
Public Sub TestStringEquality()
Dim someString As String
Assert.IsTrue(someString Is Nothing, "Of course someString is Nothing")
Assert.IsTrue(someString = String.Empty, "But it's also empty...")
Assert.IsTrue(String.Empty Is Nothing, " doesn't that mean that String.Empty = Nothing ?")
' last test fails
End Sub

[1] And that's without getting into the whole GetHashCode() trauma: When (not) to override Equals?, The Rules for GetHashCode
[2] This is tongue-in-cheek - the Is operator isn't really equality, I know. It's 'samey'.

No comments:

Popular Posts