Collection & IndexOf

B

Bernard Bourée

I have a class named "Variable" with 2 properties "Name" and "Value" and
the following class to handle a collection of Variable:

Public Class ColVariables
Inherits CollectionBase
Default Public Property Item(ByVal index As Integer) As Variable
Get
Return CType(List(index), Variable)
End Get
Set(ByVal Value As Variable)
List(index) = Value
End Set
End Property
Public Function Add(ByVal value As Variable) As Integer
Return List.Add(value)
End Function 'Add
Public Function IndexOf(ByVal value As Variable) As Integer
Return List.IndexOf(value)
End Function 'IndexOf
............................

My collection is build with:

Dim ColVar as New ColVariables
ColVar.Add(New Variable(Name, Value)

I'm trying to retrieve one item of the collection but the following code
always return -1

Dim var As New Variable(Name, Value)
Dim idx As Integer
idx = ColVar.IndexOf(var)
Idx is always -1

What is wrong ?
 
J

Jay B. Harlow [MVP - Outlook]

Bernard,
ArrayList.IndexOf (CollectionBase.List.IndexOf) uses Object.Equals to
compare two objects, so to get ColVariables.IndexOf to work you need to
override Object.Equals in your Variable class:

Something like:

Public Class Variable

Private ReadOnly m_name As String
Private ReadOnly m_value As Object

Public Sub New(ByVal name As String, ByVal value As Object)
m_name = name
m_value = value
End Sub

Public Overloads Function Equals(ByVal value As Variable) As Boolean
Return m_name = value.m_name AndAlso
m_value.Equals(value.m_value)
End Function

Public Overloads Overrides Function Equals(ByVal obj As Object) As
Boolean
If TypeOf obj Is Variable Then
Return Equals(DirectCast(obj, Variable))
Else
Return False
End If
End Function

End Class

You may want to have VariableCollection (your ColVariables) inherit from
DictionaryBase or NameObjectCollectionBase instead of CollectionBase, as it
appears you have a collection of named objects.

Hope this helps
Jay
 

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