Results 1 to 3 of 3

Thread: Issue with Lists

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Feb 2007
    Posts
    180

    Issue with Lists

    I have 2 lists, SortedValuesA and SortedValuesB.

    Heres the code I have a problem with.....

    VB Code:
    1. Dim SortedValuesb As New List(Of String())
    2.  Dim SortedValuesa As New List(Of String())
    3. .
    4. .
    5. .
    6. 'I assign a 28 arrays to List SortedValuesa
    7. 'Pull some out of A and add to B
    8. .
    9. .
    10. .
    11.    SortedValuesa = SortedValuesb
    12.    MsgBox(SortedValuesa.Count)
    13.    SortedValuesb.Clear()
    14.    MsgBox(SortedValuesa.Count)

    Now when this runs, the fist MSGBOX gives me 18, which is correct. Now the second MSGBOX gives me 0.... Thats my problem.

    By saying A=B they are now linked? So clearing B will clear A? How do I fix this?

    I'm using B as a buffer to hold temporary values pulled from A. The next step beyond this code is to do a few more layers of "stripping" until I have the final arrays that I need.

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Issue with Lists

    The List(Of T), like all other classes, are reference types. That means that your "SortedValuesa" and "SortedValuesb" are two variables that hold references to class instances in memory. When you assign SortedValuesb to SortedValuesa, you're actually making SortedValuesa refer to the same class instance in memory as SortedValuesb. It doesnt matter if you call the Clear method on SortedValuesa or SortedValuesb, as they refer to the same list.

    If you want to create a new List that is a copy of another one, use the constructor overload that allows it:
    VB.NET Code:
    1. Dim listOne As New List(Of Integer)
    2. listOne.Add(5)
    3. listOne.Add(55)
    4. listOne.Add(102)
    5. Dim listTwo As New List(Of Integer)(listOne)
    6. listOne.Clear()
    7. MessageBox.Show(listTwo.Count.ToString())
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3
    Frenzied Member obi1kenobi's Avatar
    Join Date
    Aug 2007
    Posts
    1,091

    Re: Issue with Lists

    Oh...Very nice explanation...Clears up a lot...
    Please rate helpful ppl's posts. It's the best 'thank you' you can give

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width