views:

32

answers:

2

I have a data structure (which is a class) called user_class and I want to load all the users data from a database.

Currently I have

        While SQLreader.Read()
         Hold_user.username = SQLreader(0)
         Hold_user.BlahBlahBlah = SQLreader(1)
         Hold_user.Secret_Password = SQLreader(2)
         return_value.Add(Hold_user)
        End While

Where return_value is a List of user_class and hold_user is an instance of the same class.

        Dim return_value As New List(Of user_class)
        Dim Hold_user As New user_class

As the while statement loops through the read data, SQLreader(0),(1) and (2) are updated with new data, however they also appear to be updating the stored values held in return_value....

Is entanglement a bug in Visual Studio or do I need something like ByVal, in the Add method (I know it's not ByVal I need as i've tried that :) but I hope you get what I mean. )

+5  A: 

you should create a new user_class for each iteration through the loop. Now you're putting lots of references to the same object into the list, then when you change one item, they all change, because they're all pointing to the same instance

Sander Rijken
+4  A: 

I would modify your code to instantiate a new user_class from WITHIN your while loop:

While SQLreader.Read()
    Dim Hold_user As New user_class
    Hold_user.username = SQLreader(0)
    Hold_user.BlahBlahBlah = SQLreader(1)
    Hold_user.Secret_Password = SQLreader(2)
    return_value.Add(Hold_user)
End While
Gabriel McAdams