Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving data from a VB.NET arraylist of objects

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?

like image 394
Tim the Enchanter Avatar asked Jun 30 '09 07:06

Tim the Enchanter


2 Answers

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.

like image 127
Darin Dimitrov Avatar answered Sep 30 '22 16:09

Darin Dimitrov


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
like image 25
Rowland Shaw Avatar answered Sep 30 '22 17:09

Rowland Shaw