Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize static Dictionary while creating in C++/CLI

Today I saw C# code that creates static dictionary and initializes it:

public static readonly Dictionary<string, string> dict = new Dictionary<string, string>()
        {
            {"br","value1"},
            {"cn","value2"},
            {"de","value3"},
        };

but when I decided to write same code for C++/CLI, an error occurred. Here is my attempt:

static System::Collections::Generic::Dictionary<System::String^, System::String^>^ dict = gcnew System::Collections::Generic::Dictionary<System::String^, System::String^>( )
    {
        {"br","value1"},
        {"cn","value2"},
        {"de","value3"},
    };

Can I do this and if so, how?

like image 756
Viktor Apoyan Avatar asked May 16 '11 18:05

Viktor Apoyan


People also ask

How do you initialize a dictionary?

Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.


1 Answers

C# 3.0 and later allows users to define an "initializer"; for collections, that's a series of elements, which for Dictionaries is streamlined to keys and values. C++.NET to my knowledge does not have this language feature. See this question: it's very similar: Array initialization in Managed C++. Array initializers are the ONLY such initializer in C++; other collections do not offer them in C++.

Basically, your main option is to declare a static constructor and initialize your dictionary in there.

like image 64
KeithS Avatar answered Sep 27 '22 20:09

KeithS