Array.add(item) sets all items to item!?!

Russ1984

Member
Joined
Feb 29, 2008
Messages
9
Programming Experience
Beginner
Hello,

I have created a collection that has an underlying Array for serialization to xml. The only problem I'm having with it is the 'add' method. When I add a new object is sets all the objects in the collection (and array) to the new item and I don't know why. Here is the class:
VB.NET:
 <ComClass()> _
    Public Class SerActCollection
        Implements ICollection

        Public collectionName As String
        Private AArray As ArrayList = New ArrayList()

        Public Sub New()
        End Sub

        Default Public Overloads ReadOnly _
        Property item(ByVal index As Integer) As SchemaClasses.Activity
            Get
                Return CType(AArray(index), SchemaClasses.Activity)
            End Get
        End Property

        Public Sub copyTo(ByVal a As Array, ByVal index As Integer) _
        Implements ICollection.CopyTo
            AArray.CopyTo(a, index)
        End Sub

        Public ReadOnly Property count() As Integer Implements _
        ICollection.Count
            Get
                count = AArray.Count
            End Get
        End Property

        Public ReadOnly Property syncRoot() As Object _
        Implements ICollection.SyncRoot
            Get
                Return Me
            End Get
        End Property

        Public ReadOnly Property isSynchronized() As Boolean _
        Implements ICollection.IsSynchronized
            Get
                Return False
            End Get
        End Property

        Public Function GetEnumerator() As IEnumerator _
            Implements IEnumerable.GetEnumerator

            Return AArray.GetEnumerator()
        End Function

        Public Function Add(ByVal newActivity As SchemaClasses.Activity) As Integer
            AArray.Add(newActivity)
            Return AArray.Count
        End Function
    End Class

Anybody notice what is wrong here?
 
Last edited by a moderator:
Could I see some code of you using the Add method you have declared there?

It could be something wrong with the SchemaClasses.Activity you are passing to it.
 
Couldn't say for sure without seeing the code, but I reckon that the most likely thing is that you are actually reusing the same object and overwriting the fields in it rather than creating new objects.

eg.
VB.NET:
Dim li as new ListItem
for each dr as DataRow in dt.Rows
   li.Text = dr("Text")
   lstItems.Items.Add(li)
next

That is wrong, you'd be reusing the same object - you need to do this...

VB.NET:
Dim li as ListItem
for each dr as DataRow in dt.Rows
   li = new ListItem
   li.Text = dr("Text")
   lstItems.Items.Add(li)
next
 
Last edited by a moderator:
Back
Top