Object.MemberwiseClone Creates a shallow copy of the current Object. : Object « Development « VB.Net






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

1.Object Class Supports all classes in the .NET Framework class hierarchy
2.Object.Equals Method tells whether the specified Object is equal to the current Object.
3.Create your own Equals method
4.Create Equals method based on Equals method from fields
5.Create Complex Structure with Equals and GetHashCode method
6.Object.GetType Method Gets the Type of the current instance.
7.Object.MemberwiseClone Method Creates a shallow copy of the current Object.
8.Object Class Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes.
9.Object.GetType Method Gets the Type of the current instance.
10.Object.MemberwiseClone Method Creates a shallow copy of the current Object.
11.Object Class Supports all classes in the .NET Framework class hierarchy
12.Object.GetType Method Gets the Type of the current instance.
13.No implementation. All members are inherited from Object
14.Overrides ToString function