Move objects between System.Collections.List

Hi! I have two Lists (System.Collections) and I want to move (or copy) objects from the first to the second one. This is my code

for(int x = 0;x < list1.Count;x++) {
list2.Add(list1[x])
}

But every time C# gives this error: Object reference not set to an instance of an object.

How can this problem be resolved
Thank you!


Answer this question

Move objects between System.Collections.List

  • swrong

    In the documention for System.Collection.List I noticed this little gem:
    http://msdn2.microsoft.com/en-gb/library/fkbw11z0.aspx

    So basically if you do this

    list2 = new List(list1);
    List two will have a copy of the first list.

    You should start reading the documentation for any objects you use in the .Net framework, it's generally a lot faster then asking questions. (N.B. I'm just assuming you aren't as this question wouldn't need to be asked if you are)

    Now I'm not entirely sure if this makes a Shallow (Objects are the same in both lists) or a Deep (Different objects with the same values) copy of list1 as it doesn't really say in that documentation. but I assume it's a deep copy as if you wanted a shallow copy you could simply do this:
    list2 = list1;


  • RiotAct

    Exactly the same, which is why it's a shallow copy. In order to do a deep copy, you'd need the items to implement IClonable, and would then call Clone on each item before adding it to the new collection.



  • Vedet..

    new LIst(list1) would be a shallow copy. list2 = list1 is not a copy at all, it's an assignment of a reference, that's all. Keep in mind that List is a reference type.



  • BetsyT

    Yes, the second one was null. Stupid mistake
    Thanks anyway!

  • Mark Sargent

    Yes of course, I always make that mistake. Wouldn't new List(list1) be the same as iterating through one list and adding the contents to the second as the original poster though.


  • lawrieg

    I would guess that either list1 or list2 is null.



  • Move objects between System.Collections.List