views:

19

answers:

1

Is there an easier/tidier way to deep clone a list of reference types that do not implement ICloneable.

Currently have been looping through each object in the list like so:

    Dim myListCopy As New List(Of ListObj)
    For Each lo As ListObj In MyList
        myListCopy.Add(lo.ShallowCopy)
    Next

The object ListObj contains only value types and returns a shallow memberwise.

This works however I cam across this post here: http://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c

I don't really understand whats going on in the Extension, is it possible to the shollowCopy function to an extension and avoid iteration?

A: 

If you write an extension method, it will still have to iterate over your list in some way or other. For VB.net, the extension method will look something like...

<Extension()> _
Public Function Clone(MyList as List(Of ListObj)) as List(Of ListObj)
    Dim myListCopy As New List(Of ListObj) 
    For Each lo As ListObj In MyList 
        myListCopy.Add(lo.ShallowCopy) 
    Next 
    Clone = myListCopy
End Function

Then when you need to shallow copy your list of ListObj items, you would...

Dim aList As New List(Of ListObj)
''' add stuff here
Dim anotherList As List(Of ListObj)
anotherList = aList.Clone()
Les
Thanks very much that was just what I was looking for! Was getting bogged down in all that LINQ'esque programming that I know nothing about.
baileyswalk