Add keys/values to Dictionary at declaration

vb.netVisual Studio-2008DictionaryDeclaration

vb.net Problem Overview


Very easy today, I think. In C#, its:

Dictionary<String, String> dict = new Dictionary<string, string>() { { "", "" } };

But in vb, the following doesn't work.

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) (("",""))

I'm pretty sure there's a way to add them at declaration, but I'm not sure how. And yes, I want to add them at declaration, not any other time. :) So hopefully it's possible. Thanks everyone.

I've also tried:

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) ({"",""})

And...

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {("","")}

And...

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {{"",""}}

vb.net Solutions


Solution 1 - vb.net

This is possible in VB.NET 10:

Dim dict = New Dictionary(Of Integer, String) From {{ 1, "Test1" }, { 2, "Test1" }}

Unfortunately IIRC VS 2008 uses VB.NET 9 compiler which doesn't support this syntax.

And for those that might be interested here's what happens behind the scenes (C#):

Dictionary<int, string> VB$t_ref$S0 = new Dictionary<int, string>();
VB$t_ref$S0.Add(1, "Test1");
VB$t_ref$S0.Add(2, "Test1");
Dictionary<int, string> dict = VB$t_ref$S0;

Solution 2 - vb.net

It is much the same, use the From keyword:

    Dim d As New Dictionary(Of String, String) From {{"", ""}}

However, this requires version 10 of the language, available in VS2010.

Solution 3 - vb.net

Here's a cool translation: You can also have a Generic Dictionary of strings and string array.

C#:

private static readonly Dictionary<string, string[]> dics = new Dictionary<string, string[]>
{
    {"sizes", new string[]  {"small", "medium", "large"}},
    {"colors", new string[]  {"black", "red", "brown"}},
    {"shapes", new string[]  {"circle", "square"}}
};

VB:

Private Shared ReadOnly dics As New Dictionary(Of String, String()) From {
 {"sizes", New String() {"small", "medium", "large"}},
 {"colors", New String() {"black", "red", "brown"}},
 {"shapes", New String() {"circle", "square"}}}

Cool haa :)

Solution 4 - vb.net

There's no constructor to take a KeyValuePair for a dictionary.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXstreamINsanityView Question on Stackoverflow
Solution 1 - vb.netDarin DimitrovView Answer on Stackoverflow
Solution 2 - vb.netHans PassantView Answer on Stackoverflow
Solution 3 - vb.netMikeView Answer on Stackoverflow
Solution 4 - vb.netvulkaninoView Answer on Stackoverflow