ArrayList.IndexOf() does NOT call my Class Equals()

K

Kurt Tischer

Hi!
where is my mistake? For sorting the CompareTo()-Function is called, this
part works! But, the function Equals() is never called. Why not? Please give
me a hint. Thanks!

Here my small test-class:

Class bspKlasse
Implements IComparable

Public KapTitel As String
Public atPage As Integer

Public Overloads Function CompareTo(ByVal aBspObj As Object) As Integer
Implements IComparable.CompareTo
If TypeOf aBspObj Is bspKlasse Then
Return KapTitel.CompareTo(CType(aBspObj, bspKlasse).KapTitel)
End If
Throw New ArgumentException("Object ist not a bspKlasse")
End Function

Public Overloads Function Equals(ByVal aBspObj As Object) As Boolean
If TypeOf aBspObj Is bspKlasse Then
If atPage = CType(aBspObj, bspKlasse).atPage Then Return True Else
Return False
End If
Throw New ArgumentException("Object ist not a bspKlasse")
End Function

Public Overloads Function Equals(ByVal aBspObj As Object, ByVal bBspObj As
Object) As Boolean
If TypeOf aBspObj Is bspKlasse AndAlso TypeOf bBspObj Is bspKlasse Then
If CType(aBspObj, bspKlasse).atPage = CType(bBspObj, bspKlasse).atPage
Then Return True Else Return False
End If
Throw New ArgumentException("Object ist not a bspKlasse")
End Function

End Class

Sub TestSub()
Dim aKlasseArrayList As New ArrayList

Dim indx As Integer

For indx = 0 To 10
Dim aK As New bspKlasse
aK.KapTitel = (indx Mod 3).ToString
aK.atPage = indx
aKlasseArrayList.Add(aK)
Next

Dim dK As bspKlasse
For Each dK In aKlasseArrayList
Console.WriteLine("dk.KapTitel = {0} dk.atPage = {1}", dK.KapTitel,
dK.atPage)
Next

Try
aKlasseArrayList.Sort()
Catch ex As Exception
MsgBox(ex.Message, , ex.Source)
End Try

Console.WriteLine("sorted")
For Each dK In aKlasseArrayList
Console.WriteLine("dk.KapTitel = {0} dk.atPage = {1}", dK.KapTitel,
dK.atPage)
Next

Dim tk As New bspKlasse
tk.atPage = 5
Dim inArrayAt As Integer
If aKlasseArrayList.Contains(tk) Then
inArrayAt = aKlasseArrayList.IndexOf(tk)
Console.WriteLine(inArrayAt.ToString)
End If

inArrayAt = aKlasseArrayList.IndexOf(tk)
Console.WriteLine(inArrayAt.ToString)

End Sub
 
J

Jon Skeet [C# MVP]

Kurt Tischer said:
where is my mistake? For sorting the CompareTo()-Function is called, this
part works! But, the function Equals() is never called. Why not? Please give
me a hint. Thanks!

Your Equals method doesn't explicitly override Object.Equals. Add the
Overrides keyword and it'll start working.
 
K

Kurt Tischer

Hy Jon!

VERY best thanks!!!

Overloads Overrrides ... , nice new world :)

Again, t h a n k y o u ! !
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top