24

I'm trying to determine if there's a way in Visual Basic 2008 (Express edition if that matters) to do inline collection initialization, a la JavaScript or Python:

Dim oMapping As Dictionary(Of Integer, String) = {{1,"First"}, {2, "Second"}}

I know Visual Basic 2008 supports array initialization like this, but I can't seem to get it to work for collections... Do I have the syntax wrong, or is it just not implemented?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rylee Corradini
  • 733
  • 4
  • 13
  • For future searchers, two solutions are provided here http://stackoverflow.com/questions/2629076/inline-list-initialization-in-vb-net – LosManos Oct 17 '14 at 17:04

2 Answers2

19

Visual Basic 9.0 doesn't support this yet. However, Visual Basic 10.0 will.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
8

Here are VB collection initializers using the From keyword. (Starting with Visual Studio 2010)

List:

Dim list As New List(Of String) From {"First", "Second"}

Dictionary:

Dim oMapping As New Dictionary(Of Integer, String) From {{1, "First"}, {2, "Second"}}
James Lawruk
  • 30,112
  • 19
  • 130
  • 137