2

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!

0

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you very much! this's all need
@NguyenDucLinh Most welcome! Glad I could help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.