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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With