Object.MemberwiseClone 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 = 4
p1.Name = "Jack"
p1.IdInfo = New IdInfo(1)
Dim p2 As Person = DirectCast(p1.ShallowCopy(), Person)
DisplayValues(p1)
DisplayValues(p2)
p1.Age = 3
p1.Name = "Mike"
p1.IdInfo.IdNumber = 2
DisplayValues(p1)
DisplayValues(p2)
Dim p3 As Person = p1.DeepCopy()
p1.Name = "Tom"
p1.Age = 1
p1.IdInfo.IdNumber = 4
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