This is the situation:
Class A
Implements ICloneable
Public Property Children As List(Of Child)
Public Function Clone() As Object Implements ICloneable.Clone
Return New A With {
.Children = Children.Select(Function(c) DirectCast(c.Clone(), Child)).ToList()
}
End Function
End Class
Class Child
Implements ICloneable
Public Property Parent As A
Public Function Clone() As Object Implements ICloneable.Clone
Return New Child With {
.Parent = DirectCast(Parent.Clone(), A)
}
End Function
End Class
The actual object is more complex, having several levels.
I'm not sure how to solve this because, at the moment, whenever you call Clone on the parent A class, you will end up with a circular reference.
How can I avoid this situation? Should I create my own Clone function and pass along a parameter?
The simplest solution is to just have the
Childclass not clone theParentproperty at all. When aChildclones itself, it could either leave theParentproperty the same, or just leave it null. For instance:Then, when the parent
Aclass clones itself, it could set theParentproperty of all the cloned children, like this:Alternatively, as you suggested, you could make your own
Clonemethod which takes the parent object as a parameter:It won't implement
ICloneable, but as long as you don't need it to be interchangeable with other types ofICloneableobjects, then that won't matter. Similarly, you could just overload your constructor: