Generic Lists copying references rather than creating a copiedList

Posted by Dean on Stack Overflow See other posts from Stack Overflow or by Dean
Published on 2010-03-08T13:46:16Z Indexed on 2010/03/08 13:51 UTC
Read the original article Hit count: 256

Filed under:
|
|

I was developing a small function when trying to run an enumerator across a list and then carry out some action. (Below is an idea of what I was trying to do.

When trying to remove I got a "Collection cannot be modified" which after I had actually woken up I realised that tempList must have just been assigned myLists reference rather than a copy of myLists. After that I tried to find a way to say

tempList = myList.copy

However nothing seems to exist?? I ended up writing a small for loop that then just added each item from myLsit into tempList but I would have thought there would have been another mechanism (like clone??)

So my question(s):

  • is my assumption about tempList receiving a reference to myList correct
  • How should a list be copied to another list?

        private myList as List (Of something)
    
    
    sub new()
        myList.add(new Something)
    end sub
    
    
    sub myCalledFunction()
        dim tempList as new List (Of Something)
        tempList = myList
        Using i as IEnumerator = myList.getEnumarator
           while i.moveNext
               'if some critria is met then 
               tempList.remove(i.current)
           end
        end using
    
    
    end sub
    

© Stack Overflow or respective owner

Related posts about vb.net

Related posts about generics