Copy (clone) a generic list

I want to clone a generic list that is a member of a class that implements icloneable:

PublicClass Employee

Implements ICloneable

Public FirstNameAsString

Public LastNameAsString

Public TelephoneListAs List(Of Telephone)

PublicSubNew(ByVal fnAsString,ByVal lnAsString)

Me.FirstName = fn

Me.LastName = ln

EndSub

PublicFunction Clone()AsObjectImplements System.ICloneable.Clone

'Shallow copy

Dim empAs Employee =DirectCast(Me.MemberwiseClone, Employee)

emp.TelephoneList =Me.TelephoneList

'Deep copy

'This part doesn't work-since the actual list object hasn't been cloned, I'm guessing that it's just changing each item in the list to a clone of the original item.

IfNot emp.TelephoneListIsNothingThen

ForEach tAs TelephoneIn emp.TelephoneList

t =DirectCast(t.Clone, Telephone)

Next

EndIf

Return emp

EndFunction

EndClass

PublicClass Telephone

Implements ICloneable

Public CountryCodeAsString

Public AreaCodeAsString

Public ExchangeAsString

Public DigitsAsString

Public LocationAsString

PublicFunction Clone()AsObjectImplements System.ICloneable.Clone

'Shallow copy.

Dim telAs Telephone =DirectCast(Me.MemberwiseClone, Telephone)

Return tel

EndFunction

EndClass

I can easily clone the employee object this way, but I want to make a deep copy where I'm also cloning the generic list TelephoneList and the method I'm using isn't working (I'm testing it with

MsgBox("Employee's phone list and cloned employee's phone list " & _

"refer to the same object: " & _

(em.TelephoneListIs emClone.TelephoneList).ToString)

Is there some way I can directly clone the generic list without putting it into a separate class or something? Thanks,

Dave

[10258 byte] By [dgolds] at [2007-12-24]
# 1

'This

part doesn't work-since the actual list object hasn't been cloned, I'm

guessing that it's just changing each item in the list to a clone of

the original item.

That comment is exactly correct. The code you wrote is not creating a new list, so the original and the clone have a reference to the same telephone list. All you should need to do is change this:

emp.TelephoneList = Me.TelephoneList

If Not emp.TelephoneList Is Nothing Then

For Each t As Telephone In emp.TelephoneList

t = DirectCast(t.Clone, Telephone)

Next

End If

To this:

If Not Me.TelephoneList Is Nothing Then

emp.TelephoneList = New List(Of Telephone)

For Each t As Telephone In Me.TelephoneList

emp.TelephoneList.Add( DirectCast(t.Clone, Telephone) )

Next

End If

hgen_banks at 2007-8-31 > top of Msdn Tech,Visual Basic,Visual Basic Language...