Create a "clone" of this object, not point to it

Adam Rackis, I don't like your "Of course it does", because it is not at all obvious.

If you have a string variable that you assign to another string variabe, you do not change them both when making changes to one of them. They do not point to the same physical piece of memory, so why is it obvious that classes do?

Also, the thing is not even consistent. In the following case, you will have all elements in the array pointing at the same object (they all end up with the variable Number set to 10:

SourceObject = New SomeClass
For i = 1 To 10
   SourceObject.Number = i
   ObjectArray.Add = SourceObject   
Next i

BUT, the following will give you 10 different instances:

For i = 1 To 10
   SourceObject = New SomeClass
   SourceObject.Number = i
   ObjectArray.Add = SourceObject   
Next i

Apparently the scope of the object makes a difference, so it is not at all obvious what happens.


Since you have not divulged the type of item that you are storing n your list, I assume it's something that's implementing IClonable (Otherwise, if you can, implement IClonable, or figure out a way to clone individual item in the list).

Try something like this

mySecondList = myFirstList.[Select](Function(i) i.Clone()).ToList()

Here is how you do it:

'copy one object to another via reflection properties
For Each p As System.Reflection.PropertyInfo In originalobject.GetType().GetProperties()
    If p.CanRead Then
        clone.GetType().GetProperty(p.Name).SetValue(clone, p.GetValue(OriginalObject, Nothing))
    End If
Next

in some cases when the clone object got read-only properties you need to check that first.

For Each p As System.Reflection.PropertyInfo In originalobject.GetType().GetProperties()
    If p.CanRead AndAlso clone.GetType().GetProperty(p.Name).CanWrite Then
        clone.GetType().GetProperty(p.Name).SetValue(clone, p.GetValue(OriginalObject, Nothing))
    End If
Next