|
|
Title | Initialize arrays and lists in Visual Basic .NET |
Description | This example shows how to initialize arrays and lists in Visual Basic .NET. |
Keywords | initialize arrays, initialize lists, initialize, initialization |
Categories | Syntax, 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
|
|
|
|
|
|