ToArray
The IEnumerable
type can store collections of elements. But in VB.NET programs, we often want arrays—not IEnumerable
instances.
We use the ToArray
extension to convert any IEnumerable
type to an array. Common IEnumerable
types include Lists and query expressions from LINQ.
ToArray
is found within System.Linq
. It can be called on any type instance that implements IEnumerable
. Many types implement IEnumerable
.
List
with 2 strings. This is not an array, but we can call ToArray
on it.IEnumerable
instance with 10 elements in it with Enumerable.Range
.ToArray
extension on the List
and IEnumerable
. We now have 2 arrays.For-Each
loop on both the first and second arrays to print out all the contents.Module Module1 Sub Main() ' Step 1: create a List. Dim list = New List(Of String) list.Add("BIRD") list.Add("FROG") ' Step 2: create an IEnumerable. Dim e = Enumerable.Range(0, 10) ' Step 3: use ToArray extension to convert to an array. Dim array1() = list.ToArray() Dim array2() = e.ToArray() ' Step 4: display elements. For Each value In array1 Console.WriteLine(value) Next For Each i In array2 Console.WriteLine(i) Next End Sub End ModuleBIRD FROG 0 1 2 3 4 5 6 7 8 9
I investigated the ToArray
extension Function. This Function allocates a new array. It then calls into Array.Copy
. This newly-allocated array is returned to the calling Function.
By looking at its implementation, we can determine there is no performance benefit to calling ToArray
. It can improve program syntax.
List
, offer a separate ToArray
Function. This is not an extension method.We explored the ToArray
extension Function from System.Linq
. We used it with an IEnumerable
instance and the Enumerable.Range
Function. And we investigated its internals.