views:

98

answers:

2

I want to statically define a mapped array of strings like:

var dict = {cat:50, bat:10, rat:30};

and lookup values within it like:

MessageBox.Show( dict["cat"] )
+5  A: 
Dim dict As New Dictionary(Of String, Integer)()

With dict 
    .Add("Cat", 50)
    .Add("Bat", 10)
    .Add("Rat", 30)
End With
smoore
`As New Dictionary`? or has VB changed since last I used?
dotjoe
+1 Beat me to it - but needs the "As New"
Kyle Rozendo
Is this the only way? Doesn't VB have built-in support for keyed arrays?
Jenko
@dotjoe and kyle: Indeed I do, good catch
smoore
@dotjoe,Kyle,smoore: it is just the short way of doing:Dim dict As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()which is a shorthand version of:Dim dict As Dictionary(Of String, Integer)dict = New Dictionary(Of String, Integer)()It is possible to use the shortest version due to this scenario being a "special" case: the variable is assigned with a value immediately upon decleration, the assigned value is newly created, and the variable's type is identical to the value's type.
M.A. Hanin
cool SO now recognizes the @username comment replies in your recent responses. lol at Hanin...I think you missed the part where `New` was missing from the answer.
dotjoe
@dotjoe, I sure did! Thought you guys are new to the New keyword :-)
M.A. Hanin
+4  A: 

In .NET 4.0:

Dim d As Dictionary(Of String, Integer) From
    {{"cat", 50}, {"bat", 10}, {"rat",30 }} 
Robert Harvey
This is supposed to be the preferred way of doing Collection Initialization now
masenkablast
VB.NET reports "Array initializers are only valid for arrays".. Have you actually tested this code?
Jenko
I'm trying to figure out if this code is specific to .NET 4.0. The syntax is slightly different there.
Robert Harvey
Whup. This is speculative syntax, see here: http://www.panopticoncentral.net/archive/2008/05/05/23212.aspx. It does exist in .NET 4.0, however (under slightly different syntax). See here: http://msdn.microsoft.com/en-us/library/dd293617(VS.100).aspx
Robert Harvey