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, StringDictionary, and SortedList.

Unfortunately, you cannot use this method to initialize the Stack and Queue classes. For historical reasons, the methods in those classes that add new items are called Push and Enqueue rather than Add, and this method requires the class to have an Add method.

Fortunately, you can write extension methods to give those classes Add methods. The following code creates Add methods for the Stack and Queue classes:

Module Extensions
    <Extension()>
    Public Sub Add(the_stack As Stack, value As Object)
        the_stack.Push(value)
    End Sub
 
    <Extension()>
    Public Sub Add(the_queue As Queue, value As Object)
        the_queue.Enqueue(value)
    End Sub
End Module

After you create these extension methods, you can initialize Stacks and Queues as in the following code:

Dim people_stack As New Stack() From {"Electra", "Storm", "Rogue"}
Dim people_queue As New Queue() From {"Xavier", "Anakin", "Zaphod"}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.89.123