How to Clone an Array in VB.NET

Clone method is similar to copy, it makes a clone of the original array. It is the same Type as the original Array.
  • 7462

Arrays are generally used for storing similar types of values or objects. They allow grouping variables together and allow referring to them by using an index. Arrays have an upper bound and a lower bound, which simply refer to the starting index and the ending index of a given array structure.

Array Clone

The Clone method is similar to copy, it makes a clone of the original array. It is the same Type as the original Array. However, A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. As such, if you manipulate the second array it will change the values of the first array and vice versa! Remember also that this has NOTHING to do with Passing ByVal or ByRef. You can pass the cloned array ByVal, change its values, and both Array1 and Array2 will have their values changed. In a deep copy, any objects found in the original array are also copied so that the new array does not point to the same objects as does the original array.

Syntex

'Declaration

    Public Function Clone As Object

Example:

Public Class Cloning

    Public Shared Sub Main()
        Dim A() As String = {"Manish""Sapna""Rahul""Ramesh""Rajiv"}
        Console.WriteLine(Join(A, ","))
 
        Dim B() As String = {"One""Two""Three""Four""Five""Six""Seven"}
        Console.WriteLine(Join(B, ","))
 
        Dim C() As String = A
        Console.WriteLine(Join(C, ","))
 
        Dim D() As String = A.Clone
        Console.WriteLine(Join(D, ","))
        Console.ReadLine() 

    End Sub 
End Class

Output:

s.gif

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.