Question

I am trying to retrieve the correct value from an ArrayList of objects (.NET 1.1 Framework):

I have the following defined:

Public AlList As New ArrayList

Public Class ItemInfo
    Public ItemNo As Int16
    Public ItemType As String
    Public Reports As Array
    Public PDFs As Array
End Class

The form_load event code contains:

Dim AnItemObj As New ItemInfo

Then a loop that includes:

AnItemObj.ItemNo = AFile.RecordId
AnItemObj.ItemType = temp
AlList.Add(AnItemObj)

So I should now have an ArrayList of these objects, however if I try to retrieve the data:

MsgBox(AlList(5).ItemNo)

I always get the ItemNo of the last value in the list.

What am I missing?

Was it helpful?

Solution

Put the following code:

Dim AnItemObj As New ItemInfo

inside the loop which adds AnItemObj to the list.

When you add a reference type to a list, you are only adding the reference, not the value.

This means that if you add 10 times the same instance to a list, it will add 10 times the same reference to the list. But if afterward you still have a reference to this instance you can modify its properties and as all 10 entries in the list point to the same reference in memory, all 10 entries will be modified.

OTHER TIPS

So, you've got:

Dim AnItemObj As New ItemInfo
For ...
    AnItemObj.ItemNo = AFile.RecordId
    AnItemObj.ItemType = temp
    AlList.Add(AnItemObj)
Next

What is happening here is you're creating a single object, setting the values on it, and adding a reference to it, to your list. You're then changing your ItemInfo and addign another reference to the same item to your list

You need to construct a new object on each loop, loosely thus:

Dim AnItemObj As ItemInfo
For ...
    AnItemObj = New ItemInfo
    AnItemObj.ItemNo = AFile.RecordId
    AnItemObj.ItemType = temp
    AlList.Add(AnItemObj)
Next

Are you creating a new instance of iteminfo for each increment of the loop?

I can't see your full loop code but I imagine the cause is not setting AnItemObj to a New ItemInfo object. So you just end up modifying the same object and adding it the the list again (all items in the list point to the same object).

AnItemObj = New ItemInfo()
AnItemObj.ItemNo = AFile.RecordId
AnItemObj.ItemType = temp
AlList.Add(AnItemObj)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top