VB.NET ToArray

Array

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.

Example

LINQ: language integrated query

To begin, this program creates a new IEnumerable instance with ten elements in it. This is not an array. It then calls the ToArray extension on that IEnumerable instance. We now have an Integer array.

Integer

Tip:ToArray is found within System.Linq. It can be called on any type instance that implements IEnumerable.

Tip 2:Many types implement IEnumerable. And we can even use The IEnumerable type itself—this is what we do in this program.

VB.NET program that uses ToArray

Module Module1
    Sub Main()
	' Create an IEnumerable range.
	' This is not an array.
	Dim e As IEnumerable(Of Integer) = Enumerable.Range(0, 10)

	' Use ToArray extension to convert to an array.
	Dim array() As Integer = e.ToArray()

	' Display elements.
	For Each i As Integer In array
	    Console.WriteLine(i)
	Next
    End Sub
End Module

Output

0
1
2
3
4
5
6
7
8
9

Internals

Collection abstraction: squares

I investigated the ToArray extension Function. It is located within System.Core.dll in the .NET Framework's folder. I opened this file with IL Disassembler and then navigated to System.Linq.ToArray.

IL Disassembler

Eventually, this Function allocates a new array. It then calls into Array.Copy. This newly-allocated array is returned to the calling Function. So there is no performance benefit to calling ToArray. It mainly improves the syntax.

Tip:Some collections, such as List, offer a separate ToArray Function. This is not an extension method.

List

Summary

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, which allocate a new array and call Array.Copy.


VB.NET: LINQ