Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Collection Initializers
 Syntax
 Creating a Collection by Using a Collection Initializer
 Nesting Collection Initializers
 Related Topics
 See also
 How to: Create an Add Extension Method Used by a Collection Initializer
 Example
 See also
  How to: Create a Collection Used by a Collection Initializer
 Example
 See also
  Source/Reference

VB.NET Collection Initializers

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.

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. The following examples show various ways to use collection initializers to create collections.

VB
' 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.

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.

VB
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.

VB
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 Initializer

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.

VB
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.

VB
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. 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.

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.

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

The previous code example is equivalent to the following code.

VB
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.

Related Topics

Title Description
How to: Create an Add Extension Method Used by a Collection Initializer 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 Shows how to enable use of a collection initializer by including an Add method in a collection class that implements IEnumerable.

See also

How to: Create an Add Extension Method Used by a Collection Initializer

When you use a collection initializer to create a collection, the Visual Basic compiler searches for an Add method of the collection type for which the parameters for the Add method match the types of the values in the collection initializer. This Add method is used to populate the collection with the values from the collection initializer.

If no matching Add method exists and you cannot modify the code for the collection, you can add an extension method called Add that takes the parameters that are required by the collection initializer. This is typically what you need to do when you use collection initializers for generic collections.

Example

The following example shows how to add an extension method to the generic List<T> type so that a collection initializer can be used to add objects of type Employee. The extension method enables you to use the shortened collection initializer syntax.

VB
Public Class Employee
    Public Property Id() As Integer
    Public Property Name() As String
End Class
VB
Imports System.Runtime.CompilerServices

Module Module1

    <Extension()>
    Sub Add(ByVal list As List(Of Employee), ByVal id As Integer,
                                             ByVal name As String)
        list.Add(New Employee With {.Id = id, .Name = name})
    End Sub

End Module
VB
Sub Main()
    Dim employees = New List(Of Employee) From {{1, "Adams, Ellen"},
                                                {2, "Hamilton, James R."},
                                                {3, "Ihrig, Ryan"}}
End Sub

See also

How to: Create a Collection Used by a Collection Initializer

When you use a collection initializer to create a collection, the Visual Basic compiler searches for an Add method of the collection type for which the parameters for the Add method match the types of the values in the collection initializer. This Add method is used to populate the collection with the values from the collection initializer.

Example

The following example shows an OrderCollection collection that contains a public Add method that a collection initializer can use to add objects of type Order. The Add method enables you to use the shortened collection initializer syntax.

VB
Public Class Customer
    Public Property Id As Integer
    Public Property Name As String
    Public Property Orders As OrderCollection

    Public Sub New(ByVal id As Integer, ByVal name As String, ByVal orders As OrderCollection)
        Me.Id = id
        Me.Name = name
        Me.Orders = orders
    End Sub
End Class

Public Class Order
    Public Property Id As Integer
    Public Property CustomerId As Integer
    Public Property OrderDate As DateTime

    Public Sub New(ByVal id As Integer,
                   ByVal customerId As Integer,
                   ByVal orderDate As DateTime)
        Me.Id = id
        Me.CustomerId = customerId
        Me.OrderDate = orderDate
    End Sub
End Class
VB
Public Class OrderCollection
    Implements IEnumerable(Of Order)

    Dim items As New List(Of Order)

    Public Property Item(ByVal index As Integer) As Order
        Get
            Return CType(Me(index), Order)
        End Get
        Set(ByVal value As Order)
            items(index) = value
        End Set
    End Property

    Public Sub Add(ByVal id As Integer, ByVal customerID As Integer, ByVal orderDate As DateTime)
        items.Add(New Order(id, customerID, orderDate))
    End Sub

    Public Function GetEnumerator() As IEnumerator(Of Order) Implements IEnumerable(Of Order).GetEnumerator
        Return items.GetEnumerator()
    End Function

    Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Me.GetEnumerator()
    End Function
End Class
VB
Imports System.Runtime.CompilerServices

Module Module1

    <Extension()>
    Sub Add(ByVal genericList As List(Of Customer),
            ByVal id As Integer,
            ByVal name As String,
            ByVal orders As OrderCollection)

        genericList.Add(New Customer(id, name, orders))
    End Sub
End Module
VB
Dim customerList = New List(Of Customer) From
  {
    {1, "John Rodman", New OrderCollection From {{9, 1, #6/12/2008#},
                                                 {8, 1, #6/11/2008#},
                                                 {5, 1, #5/1/2008#}}},
    {2, "Ariane Berthier", New OrderCollection From {{2, 2, #1/18/2008#},
                                                     {4, 2, #3/8/2008#},
                                                     {6, 2, #3/18/2008#},
                                                     {7, 2, #5/14/2008#},
                                                     {5, 2, #4/4/2008#}}},
     {3, "Brian Perry", New OrderCollection From {{1, 3, #1/15/2008#},
                                                  {3, 3, #3/8/2008#}}}
  }

See also

Source/Reference


©sideway

ID: 200900015 Last Updated: 9/15/2020 Revision: 0 Ref:

close

References

  1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
  3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
  4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
  5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
  6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
  7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
  8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
  9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
  10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
  11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
  12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
  13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
  14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
  15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
  16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
  17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
  18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
  19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
  20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
  21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
  22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
close

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 339

Reference 79

Computer

Hardware 249

Software

Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19

Programming

Web 289

Unicode 504

HTML 66

CSS 65

SVG 46

ASP.NET 270

OS 429

DeskTop 7

Python 72

Knowledge

Mathematics

Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1


Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019