ICloneable interface in VB.NET

The ICloneable interface contains one member, Clone, it is a procedure that can create a true, distinct copy of an object and all its dependent object.
  • 4719

Introduction to ICloneable

The ICloneable interface contains one member, Clone, which is intended to support cloning beyond that supplied by MemberwiseClone. It is a procedure that can create a true, distinct copy of an object and all its dependent object, is to rely on the serialization features of the .NET framework.

There are two ways to clone an instance:

An instance is an actual object created to the specification defined by a class.

  1. Shallow copy - may be linked to data shared by both the original and the copy
  2. Deep copy - contains the complete encapsulated data of the original object

Syntex

<ComVisibleAttribute(True)> _
Public Interface ICloneable

Example

Public Class value
    Implements ICloneable
 
    Public i As Integer
    Public j As Integer
 
    Sub New(aa As Integer, bb As Integer)
        i = aa
        j = bb
    End Sub
 
    Public Overloads Function ToString() As String
        Return "(" & i & "," & j & ")"
    End Function
 
    Public Overridable Function Cloning() As Object _
                       Implements ICloneable.Clone
        Return New value(i, j)
    End 
Function
End Class
 
Module Test
    Sub Main()
        Dim v1 As New value(10, 9)
        Dim v2 As value
 
        v2 = v1.Cloning()
        Console.WriteLine("Given Object: " & v1.ToString())
        Console.WriteLine("Object after Cloned: " & v2.ToString())
        Console.ReadLine()
    End 
Sub
End Module

Output

clone.gif

Categories

More Articles

© 2013 dotNetheaven. All rights reserved.