Поделиться через


Collection Initializers (Visual Basic)

Collection initializers provide a shortened syntax that enables you to create a collection and populate it with an initial set of values. Collection initializers are useful when you are creating a collection from a set of known values, for example, a list of menu options or categories, an initial set of numeric values, a static list of strings such as day or month names, or geographic locations such as a list of states that is used for validation.

For more information about collections, see Collections (C# and Visual Basic).

You identify a collection initializer by using the From keyword followed by braces ({}). This is similar to the array literal syntax that is described in Arrays in Visual Basic. The following examples show various ways to use collection initializers to create collections.

' Create an array of type String(). 
Dim winterMonths = {"December", "January", "February"}

' Create an array of type Integer() 
Dim numbers = {1, 2, 3, 4, 5}

' Create a list of menu options. (Requires an extension method 
' named Add for List(Of MenuOption) 
Dim menuOptions = New List(Of MenuOption) From {{1, "Home"},
                                                {2, "Products"},
                                                {3, "News"},
                                                {4, "Contact Us"}}

Note

C# also provides collection initializers. C# collection initializers provide the same functionality as Visual Basic collection initializers. For more information about C# collection initializers, see Object and Collection Initializers (C# Programming Guide).

Syntax

A collection initializer consists of a list of comma-separated values that are enclosed in braces ({}), preceded by the From keyword, as shown in the following code.

Dim names As New List(Of String) From {"Christa", "Brian", "Tim"}

When you create a collection, such as a List<T> or a Dictionary<TKey, TValue>, you must supply the collection type before the collection initializer, as shown in the following code.

Public Class AppMenu
    Public Property Items As List(Of String) =
        New List(Of String) From {"Home", "About", "Contact"}
End Class

Note

You cannot combine both a collection initializer and an object initializer to initialize the same collection object. You can use object initializers to initialize objects in a collection initializer.

Creating a Collection by Using a Collection Intializer

When you create a collection by using a collection initializer, each value that is supplied in the collection initializer is passed to the appropriate Add method of the collection. For example, if you create a List<T> by using a collection initializer, each string value in the collection initializer is passed to the Add method. If you want to create a collection by using a collection initializer, the specified type must be valid collection type. Examples of valid collection types include classes that implement the IEnumerable<T> interface or inherit the CollectionBase class. The specified type must also expose an Add method that meets the following criteria.

  • The Add method must be available from the scope in which the collection initializer is being called. The Add method does not have to be public if you are using the collection initializer in a scenario where non-public methods of the collection can be accessed.

  • The Add method must be an instance member or Shared member of the collection class, or an extension method.

  • An Add method must exist that can be matched, based on overload resolution rules, to the types that are supplied in the collection initializer.

For example, the following code example shows how to create a List(Of Customer) collection by using a collection initializer. When the code is run, each Customer object is passed to the Add(Customer) method of the generic list.

Dim customers = New List(Of Customer) From
    {
        New Customer("City Power & Light", "http://www.cpandl.com/"),
        New Customer("Wide World Importers", "http://www.wideworldimporters.com/"),
        New Customer("Lucerne Publishing", "http://www.lucernepublishing.com/")
    }

The following code example shows equivalent code that does not use a collection initializer.

Dim customers = New List(Of Customer) 
customers.Add(New Customer("City Power & Light", "http://www.cpandl.com/"))
customers.Add(New Customer("Wide World Importers", "http://www.wideworldimporters.com/"))
customers.Add(New Customer("Lucerne Publishing", "http://www.lucernepublishing.com/"))

If the collection has an Add method that has parameters that match the constructor for the Customer object, you could nest parameter values for the Add method within collection initializers, as discussed in the next section. If the collection does not have such an Add method, you can create one as an extension method. For an example of how to create an Add method as an extension method for a collection, see How to: Create an Add Extension Method Used by a Collection Initializer (Visual Basic). For an example of how to create a custom collection that can be used with a collection initializer, see How to: Create a Collection Used by a Collection Initializer (Visual Basic).

Nesting Collection Initializers

You can nest values within a collection initializer to identify a specific overload of an Add method for the collection that is being created. The values passed to the Add method must be separated by commas and enclosed in braces ({}), like you would do in an array literal or collection initializer.

When you create a collection by using nested values, each element of the nested value list is passed as an argument to the Add method that matches the element types. For example, the following code example creates a Dictionary<TKey, TValue> in which the keys are of type Integer and the values are of type String. Each of the nested value lists is matched to the Add method for the Dictionary.

Dim days = New Dictionary(Of Integer, String) From
    {{0, "Sunday"}, {1, "Monday"}}

The previous code example is equivalent to the following code.

Dim days = New Dictionary(Of Integer, String)
days.Add(0, "Sunday")
days.Add(1, "Monday")

Only nested value lists from the first level of nesting are sent to the Add method for the collection type. Deeper levels of nesting are treated as array literals and the nested value lists are not matched to the Add method of any collection.

Title

Description

How to: Create an Add Extension Method Used by a Collection Initializer (Visual Basic)

Shows how to create an extension method called Add that can be used to populate a collection with values from a collection initializer.

How to: Create a Collection Used by a Collection Initializer (Visual Basic)

Shows how to enable use of a collection initializer by including an Add method in a collection class that implements IEnumerable.

See Also

Tasks

How to: Initialize an Array Variable in Visual Basic

How to: Create a List of Items

Reference

New Operator (Visual Basic)

Concepts

Object Initializers: Named and Anonymous Types (Visual Basic)

Auto-Implemented Properties (Visual Basic)

Local Type Inference (Visual Basic)

Anonymous Types (Visual Basic)

Introduction to LINQ in Visual Basic

Other Resources

Collections (C# and Visual Basic)

Arrays in Visual Basic