COLLECTION INITIALIZERS

Initializers allow you to easily initialize collection classes that have an Add method. To initialize a collection, follow the variable’s instantiation with the keyword From and then a series of comma-separated values inside braces.

For example, the following code snippet initializes an ArrayList, StringCollection, and generic List(Of Person). Notice how the generic List’s initializer includes a series of new Person objects that are initialized with the With keyword.

Dim numbers As New ArrayList() From {1, 2, 3}
Dim names As New StringCollection() From {"Alice", "Bob", "Cynthia"}
Dim authors As New List(Of Person) From {
    New Person() With {.FirstName = "Simon", .LastName = "Green"},
    New Person() With {.FirstName = "Christopher", .LastName = "Moore"},
    New Person() With {.FirstName = "Terry", .LastName = "Pratchett"}
}

If a collection’s Add method takes more than one parameter, simply include the appropriate values for each item inside their own sets of braces. The following code uses this method to initialize a NameValueCollection and a Dictionary with Integer keys and String values:

Dim phone_numbers As New NameValueCollection() From {
    {"Ashley", "502-253-3748"},
    {"Jane", "505-847-2984"},
    {"Mike", "505-847-3984"},
    {"Shebly", "502-487-4939"}
}
Dim greetings As New Dictionary(Of Integer, String) From {
    {1, "Hi"},
    {2, "Hello"},
    {3, "Holla"}
}

The same technique works for other collections that need two values such as ListDictionary, Hashtable, HybridDictionary, ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.