Copy (clone) a generic list
I want to clone a generic list that is a member of a class that implements icloneable:
PublicClass EmployeeImplements ICloneablePublic FirstNameAsStringPublic LastNameAsStringPublic TelephoneListAs List(Of Telephone)PublicSubNew(ByVal fnAsString,ByVal lnAsString)Me.FirstName = fnMe.LastName = lnEndSubPublicFunction Clone()AsObjectImplements System.ICloneable.Clone'Shallow copyDim 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.TelephoneListIsNothingThenForEach tAs TelephoneIn emp.TelephoneListt =
DirectCast(t.Clone, Telephone)NextEndIfReturn empEndFunctionEndClassPublicClass TelephoneImplements ICloneablePublic CountryCodeAsStringPublic AreaCodeAsStringPublic ExchangeAsStringPublic DigitsAsStringPublic LocationAsStringPublicFunction Clone()AsObjectImplements System.ICloneable.Clone'Shallow copy.Dim telAs Telephone =DirectCast(Me.MemberwiseClone, Telephone)Return telEndFunctionEndClassI 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.TelephoneList
Is 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

