Object.MemberwiseClone Method Creates a shallow copy of the current Object.
Public Class IdInfo
Public IdNumber As Integer
Public Sub New(IdNumber As Integer)
Me.IdNumber = IdNumber
End Sub
End Class
Public Class Person
Public Age As Integer
Public Name As String
Public IdInfo As IdInfo
Public Function ShallowCopy() As Person
Return DirectCast(Me.MemberwiseClone(), Person)
End Function
Public Function DeepCopy() As Person
Dim other As Person = DirectCast(Me.MemberwiseClone(), Person)
other.IdInfo = New IdInfo(Me.IdInfo.IdNumber)
Return other
End Function
End Class
Module Example
Public Sub Main()
Dim p1 As New Person()
p1.Age = 42
p1.Name = "Jack"
p1.IdInfo = New IdInfo(6565)
Dim p2 As Person = DirectCast(p1.ShallowCopy(), Person)
DisplayValues(p1)
DisplayValues(p2)
p1.Age = 32
p1.Name = "James"
p1.IdInfo.IdNumber = 7
DisplayValues(p1)
DisplayValues(p2)
Dim p3 As Person = p1.DeepCopy()
p1.Name = "George"
p1.Age = 39
p1.IdInfo.IdNumber = 8
DisplayValues(p1)
DisplayValues(p3)
End Sub
Public Sub DisplayValues(p As Person)
Console.WriteLine(" Name: {0:s}, Age: {1:d}", p.Name, p.Age)
Console.WriteLine(" Value: {0:d}", p.IdInfo.IdNumber)
End Sub
End Module
Related examples in the same category