Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleInitialize arrays and lists in Visual Basic .NET
DescriptionThis example shows how to initialize arrays and lists in Visual Basic .NET.
Keywordsinitialize arrays, initialize lists, initialize, initialization
CategoriesSyntax, Tips and Tricks
 
You can initialize arrays by specifying items inside brackets and separated by commas. The following code initializes an array of strings. It then uses it as a LIstBox's DataSource.
 
' Use array initialization syntax.
Dim fruits() As String = _
{ _
    "Apple", _
    "Banana", _
    "Cherry" _
}
lstFruits.DataSource = fruits
 
Unfortunately you cannot use the same syntax to initialize a List. You can, however, use a Lists's AddRange method to add a series of objects to the List. The AddRange method takes as a parameter an object that implements IEnumerable. An array implements IEnumerable so you can use the array initialization syntax to create an array and then pass it to AddRange.

The following code uses this method to initialize a List(Of String).

 
' Initialize a List using an array.
Dim cookies_list As New List(Of String)()
cookies_list.AddRange(New String() _
    { _
        "Chocolate Chip", _
        "Snickerdoodle", _
        "Peanut Butter" _
    })
lstCookies.DataSource = cookies_list
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated