Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I call ArrayList.ToArray?

The code base where I work has code similar to the following in a few places:

Dim i As Integer
Dim ints As New ArrayList
ints.Add(1)

'... lets say we add more Integers

For each i in ints.ToArray(GetType(Integer))
'Do something
Next

I'm wondering what benefit is gained from the .ToArray(GetType(Integer)) since omitting that has nearly the same result at run-time. That is calling For Each i In ints. The only difference I see is that if some type other than Integer is in the ArrayList the resulting error message is more helpful if you do not call .ToArray()

Why would I want to use ToArray(type) on an ArrayList if I will be doing a For Each loop where the type is already specified?

like image 924
Daniel Avatar asked Feb 13 '26 06:02

Daniel


2 Answers

Why would I want to use ToArray(type) on an ArrayList if I will be doing a For Each loop where the type is already specified?

In general, you likely don't want to do this. Calling ToArray() actually creates a new array of your values.

The one place where this could be beneficial is if your loop is going to modify the ArrayList. You can't modify most collections while enumerating them, so you'd get an exception. By adding the ToArray call, you are enumerating a copy of the collection (as an array), so you can modify the original.

Note that, in general, if that's the case, I'd use ToList(), and not ToArray(), as it's typically a bit more efficient (often one fewer memory allocation). I'd also recommend using List(Of Integer) instead of ArrayList for any new code, as you get type safety.

like image 157
Reed Copsey Avatar answered Feb 15 '26 20:02

Reed Copsey


You do not need to call ToArray on an ArrayList in a For each loop: i is already declared as Integer, so the type conversion will be performed for you automatically.

Sometimes you may need to call an array on results of a query to copy the data into memory. One place where it gives you advantages is copying results of a database query into memory, because you can close the connection sooner. In addition, calling ToList could help you in situations when a query would otherwise reference a modified variable, or when IEnumerable is expensive to produce multiple times.

like image 20
Sergey Kalinichenko Avatar answered Feb 15 '26 18:02

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!