0

I want to copy the content of one List(Of Object) to another and modify a single value. Is there a way to remove the reference?

In the code sample I get the output 'test2 test2' when I expect 'test1 test2'.

Module Module1

Sub Main()
    Dim ListOfSample As New List(Of sample)
    Dim var1 As New sample
    var1.Name = "test"
    ListOfSample.Add(var1)
    ListOfSample.Add(var1)

    Dim NewListOfSample As New List(Of sample)

    NewListOfSample.AddRange(ListOfSample)
    NewListOfSample(1).Name = "test2"

    Console.Write(NewListOfSample(0).Name & " " & NewListOfSample(1).Name)
End Sub

End Module

Public Class sample
    Public Name As String
End Class
cornholio
  • 3
  • 2
  • This can be helpful, unless this a same problem: [http://stackoverflow.com/a/78612/1565525](http://stackoverflow.com/a/78612/1565525) – Fabio Mar 24 '16 at 14:27
  • The key point here is that you *only* have one `sample` object, and you have it in both lists twice. So all of your list entries refer to the same object and changing one *is changing that one object*. – crashmstr Mar 24 '16 at 14:31

2 Answers2

1

Since your list is a list of Objects, when you perform add range, you are not adding "copies", instead you are adding the pointers (references) to the same objects that are in your original list.

You will need to clone all of your objects in the first list, and then add those clones to your second list. When it comes to cloning there are several different ways in .NET. Here's a post on getting deep copies of objects that does a good job explaining your options: Deep Copy of an Object

You can either create a clone method on your "sample" object to return a newly initialized copy of itself, or you can use some of the serialization methods mentioned in the post I linked to.

Community
  • 1
  • 1
davidallyoung
  • 1,302
  • 11
  • 15
0

In the line NewListOfSample.AddRange(ListOfSample) you're adding references to your new list. So whatever you change in your new list will update the reference in your original list (they're both pointing to the same objects). You need to add new instances of Sample to the second list for it to contain independent items.

auburg
  • 1,373
  • 2
  • 12
  • 22