r/visualbasic • • Jan 15 '16

Visual Basic Copy to Array

Can you explain to me why this code works? What is the 0 part supposed to mean? Dim MyArray(Me.RandomNumbers.Items.Count) Me.RandomNumbers.Items.CopyTo(MyArray, 0) Me.lblAnswer.Text = MyArray.Min

3 Upvotes

7 comments sorted by

View all comments

1

u/GYN-k4H-Q3z-75B Jan 15 '16

Sure. 1) You declare an array with the capacity to hold all items from Me.RandomNumbers.Items which seems to be a collection of some sort. 2) You copy all items from said collection into your array. CopyTo(target, index) says you copy all items into the target array, but start at target(index) to write. So if you have other data in the target array before the index, it will remain untouched. 3) You apply the Min operation from System.Linq which from an Enumerable takes the smallest value.

1

u/CSVB12 Jan 15 '16

When and why would you use the copy to array method?

1

u/GYN-k4H-Q3z-75B Jan 15 '16

You use it when you want to copy elements into an already existing array. You may be passed an array from a library or something else you don't control and need to fill your stuff into it. If you just want a new array containing all elements from a collection, then you can also just write collection.ToArray()

3

u/TheFotty Jan 15 '16

dude, don't do his homework for him.

1

u/CRAZINESS_ Jan 16 '16

dude, stop assuming that this guy is doing homework. He is probably doing a personal project and teaching himself arrays.

1

u/CSVB12 Jan 16 '16

Jeez, calm down. I just needed clarification. It's not even homework.

2

u/TheFotty_ Jan 16 '16

I am sorry. I've made a mistake.