Resizing an array

ARC

Well-known member
Joined
Sep 9, 2006
Messages
63
Location
Minnesota
Programming Experience
Beginner
This is set up with the ability to add and remove user names from a listbox. Below, I have this in the Remove User code in order to shift all the data past the tempIndex (the index that was removed) all the way up to the last entry, all down 1.

Because totalUsers provides a value that's +1 than the length of the LoginArray (because the array holds 0 as it's first cell), I resize the LoginArray by using the totalUsers variable. The question I have then, i have then is, will this simply delete the last cell of the array and all the info in it? I guess I'm assuming that if you resize an array that's 6 length down to a 5 length that it'll just get rid of that 6th cell and all the data in it.

VB.NET:
        For i = tempIndex To totalUsers Step 1
            LoginArray(i).Name = LoginArray(i + 1).Name
            LoginArray(i).Pass = LoginArray(i + 1).Pass
        Next i
        
        ReDim Preserve LoginArray(totalUsers - 1)

        totalUsers -= 1
 
Last edited:
yes it will copy element 1 to element 0, element 2 to element 1, element 3 to element 2, etc. then the ReDim Preserve LoginArray(totalUsers - 1), will remove the highest index.
 
The question I have then, i have then is, will this simply delete the last cell of the array and all the info in it? I guess I'm assuming that if you resize an array that's 6 length down to a 5 length that it'll just get rid of that 6th cell and all the data in it.
No, Redim statement creates a new array and deletes the previous. Preserve keyword determines if element values will be copied from old array to new.

Using a List(Of Yourstructure) instead of array would save you lots of coding and give better performance.
 
Wow... basically just replaced three large chunks of code, with two tiny lines of code. Thanks a lot for the List(Of Structure) suggestion!
 
Dont forget about Dictionary(Of TKey, TValue) either :) I expect your Login usernames are unique, so you could use

VB.NET:
Public allUsers As New Dictionary(Of String, LoginUser)

where the String could be the unique name. To remove a user, you'd then just use

VB.NET:
        Dim blnRemoved As Boolean = allUsers.Remove("JOEBLOGGS")
 
Back
Top