Nguyen Duc Linh Nguyen Duc Linh - 3 months ago 56
Vb.net Question

Vb.net: Array.clear Clean related Array issue

I have trouble with Array.clear function

This is the simple code:

Dim Array1() As Double = {1, 2}
Dim Array2(UBound(Array1)) As Double
Array2 = Array1
Array.Clear(Array1, 0, Array1.Length)


After do the Array.Clear, it is not only Array 1 is Cleaned but also Array 2 is cleaned.

What happened here? What can i do to prevent this?

Thank you!

Answer

What's happening:

Array2 = Array1

The above statement doesn't copy the elements of Array1 into Array2, instead the above statement only copies the pointer as mentioned in the link below

Assigning one array to another

Because of the above, when you do

Array.Clear(Array1, 0, Array1.Length)

The values of Array1 are changed to 0 and Array2 points to the new values of Array 1 i.e., all 0s.

How to prevent it:

Use Array copy which copies the elements.

Dim Array1() As Double = {1, 2}
Dim Array2(UBound(Array1)) As Double
Array.Copy(Array1,Array2,Array2.Length) //Array.Copy(source, target, target.Length)
Array.Clear(Array1, 0, Array1.Length)